Python| os.path.commonpath() 方法
Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。 os.path模块是Python中OS 模块的子模块,用于常见的路径名操作。
Python中的os.path.commonpath()
方法用于获取路径列表中最长的公共子路径。如果指定的路径列表包含绝对路径和相对路径,或者为空,则此方法引发ValueError 。与os.path.commonpath()
方法不同,返回值是有效路径。
例如,考虑以下路径列表:
list of paths Longest common sub-path
['/home/User/Photos', /home/User/Videos'] /home/User
['/usr/local/bin', '/usr/lib'] /usr
Syntax: os.path.commonpath(list)
Parameter:
path: A list of path-like object. A path-like object is either a string or bytes object representing a path.
Return Type: This method returns a string value which represents the longest common sub-path in the specified list.
代码 #1:使用 os.path.commonpath() 方法
# Python program to explain os.path.commonpath() method
# importing os module
import os
# List of Paths
paths = ['/home/User/Desktop', '/home/User/Documents',
'/home/User/Downloads']
# Get the
# longest common sub-path
# in the specified list
prefix = os.path.commonpath(paths)
# Print the
# longest common sub-path
# in the specified list
print("Longest common sub-path:", prefix)
# List of Paths
paths = ['/usr/local/bin', '/usr/bin']
# Get the
# longest common sub-path
# in the specified list
prefix = os.path.commonpath(paths)
# Print the
# longest common sub-path
# in the specified list
print("Longest common sub-path:", prefix)
Longest common sub-path: /home/User
Longest common sub-path: /usr
代码 #2:使用 os.path.commonpath() 方法
# Python program to explain os.path.commonpath() method
# importing os module
import os
# List of Paths
paths = ['/usr/local/bin', 'usr/bin']
# Get the
# longest common sub-path
# in the specified list
prefix = os.path.commonpath(paths)
# Print the
# longest common sub-path
# in the specified list
print("Longest common sub-path:", prefix)
# The above code will raise
# ValueError as list of paths
# contains both absolute and
# relative path
Traceback (most recent call last):
File "oscommonpath.py", line 12, in
prefix = os.path.commonpath(paths)
File "/usr/lib/python3.6/posixpath.py", line 505, in commonpath
raise ValueError("Can't mix absolute and relative paths") from None
ValueError: Can't mix absolute and relative paths
注意:如果指定的列表为空, os.path.commonpath()
方法也会引发ValueError 。
参考: https://docs。 Python.org/3/library/os.path.html