os.path 模块中的 normpath(path) 方法用于获取提供的路径名的规范化路径名。路径规范化涉及通过删除冗余组件来简化路径名,例如额外的分隔符 (//)、对当前目录的引用 (./) 和对父目录的引用 (../).此方法可确保在不同平台上以一致且有效的格式表示路径。
在 Windows 操作系统上,此方法将正斜杠转换为反斜杠,因此此规范化可能会更改包含符号链接的路径的含义。
语法
以下是该方法的语法 -
os.path.normpath(path)
参数
以下是其参数的详细信息 -
- path: 此参数表示类似路径的对象,它可以是表示文件系统路径的字符串或字节对象,也可以是实现 'os.PathLike“协议。
返回值
该方法返回一个字符串,该字符串表示所提供路径的规范化版本。
例子让我们探索一些示例来了解 os.path.normpath() 方法的工作原理。
例以下示例使用 os.path.normpath() 方法获取输入路径 'A//B/C/./../D' 的
# Import the os module
import os
# Normalizing a path
path = 'A//B/C/./../D'
normalized_path = os.path.normpath(path)
# Print the results
print(normalized_path)
# Verify the type of the normpath output
print('Type of the normpath output:',type(normalized_path))
输出
在执行上述代码时,您将获得以下输出 -
A/B/D
Type of the normpath output: class 'str'>
Type of the normpath output: class 'str'>
如果您在 Windows 操作系统中执行上述程序,您将获得以下输出。正斜杠或转换为反斜杠。
A\B\D
Type of the normpath output: class 'str'>
Type of the normpath output: class 'str'>
例
在此示例中,os.path.normpath() 方法从包含符号链接 “..” 的输入路径中获取规范化路径,通常这是指父目录。
# Import the os module
import os
# Normalizing a path
path = 'A/foo/../B'
normalized_path = os.path.normpath(path)
# Print the results
print('The resultant normalized path:',normalized_path)
输出
在我们的在线编译器中执行上述代码时,将获得以下输出 -
The resultant normalized path: A/B
例
在此示例中,路径提供给 os.path.normpath() 方法,其中 “.” 作为路径段,以获取规范化路径。
# Import the os module
import os
# Normalizing a path
path = 'mydir/./myfile.txt'
normalized_path = os.path.normpath(path)
# Print the results
print('The resultant normalized path:',normalized_path)
输出
在我们的在线编译器中执行上述代码时,将获得以下输出 -
The resultant normalized path: mydir/myfile.txt
例
这是另一个使用 os.path.normpath() 方法对以下路径名 “D://a//b//c/../e/./myfile.txt” 进行规范化的示例。
# Import the os module
import os
# Normalizing a path
path = 'D://a//b//c/../e/./myfile.txt'
normalized_path = os.path.normpath(path)
# Print the results
print('The resultant normalized path:',normalized_path)
输出
在我们的在线编译器中执行上述代码时,将获得以下输出 -
The resultant normalized path: D:/a/b/e/myfile.txt