Python中的OS模块提供了与操作系统进行交互的功能。操作系统属于Python的标准实用程序模块。该模块提供了使用依赖于操作系统的功能的便携式方法。 os.path模块是Python中OS模块的子模块,用于通用路径名操作。
os.path.normpath()
Python中的方法用于规范化指定的路径。在路径规范化过程中,所有冗余分隔符和up-level引用均折叠。
例如: A //B,A /B /,A /./B和A /foo /../B都将被标准化为A /B。在Windows操作系统上,路径中的任何正斜杠('/')都将转换为反斜杠('\')。
用法: os.path.normpath(path)
参数:
path:代表文件系统路径的path-like对象。
返回类型:此方法返回代表标准化路径的字符串值。
代码1:用于os.path.normpath()
方法
# Python program to explain os.path.normpath() method
# importing os.path module
import os.path
# Path
path = '/home//user/Documnets'
# Normalize the specified path
# using os.path.normpath() method
norm_path = os.path.normpath(path)
# Print the normalized path
print(norm_path)
# Path
path = '/home/./Documents'
# Normalize the specified path
# using os.path.normpath() method
norm_path = os.path.normpath(path)
# Print the normalized path
print(norm_path)
# Path
path = '/home/user/temp/../Documents'
# Normalize the specified path
# using os.path.normpath() method
norm_path = os.path.normpath(path)
# Print the normalized path
print(norm_path)
输出:
/home/user/Documnets
/home/Documents
/home/user/Documents
代码2:用于os.path.normpath()
方法(在Windows上)
# Python program to explain os.path.normpath() method
# importing os.path module
import os.path
# Path
path = r'C:/Users'
# Normalize the specified path
# using os.path.normpath() method
norm_path = os.path.normpath(path)
# Print the normalized path
print(norm_path)
# Path
path = r'C:\Users\.\Documents'
# Normalize the specified path
# using os.path.normpath() method
norm_path = os.path.normpath(path)
# Print the normalized path
print(norm_path)
# Path
path = r'C:\Users\admin\temp\..\Documents'
# Normalize the specified path
# using os.path.normpath() method
norm_path = os.path.normpath(path)
# Print the normalized path
print(norm_path)
输出:
C:\\Users
C:\\Users\\Documents
C:\\Users\\admin\\Documents