Python| os.path.normpath() 方法
Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。 os.path模块是Python中OS 模块的子模块,用于常见的路径名操作。
Python中的os.path.normpath()方法用于规范化指定路径。在路径规范化过程中,所有多余的分隔符和上层引用都被折叠。
例如: A//B 、 A/B/ 、 A/./B和A/foo/../B都将归一化为 A/B。
在 Windows 操作系统上,路径中的任何正斜杠 ('/') 都将转换为反斜杠 ('\')。
Syntax: os.path.normpath(path)
Parameter:
path: A path-like object representing a file system path.
Return Type: This method returns a string value which represents the normalized path.
代码 #1:使用os.path.normpath()方法
Python3
# Python program to explain os.path.normpath() method
# importing os.path module
import os.path
# Path
path = '/home//user/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/./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)
Python3
# 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)
输出
/home/user/Documents
/home/Documents
/home/user/Documents
代码 #2:使用os.path.normpath()方法(在 Windows 上)
Python3
# 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
参考: https://docs。 Python.org/3/library/os.path.html