Python os.path.commonprefix()
Python中的os.path.commonprefix()方法用于获取路径列表中的最长公共路径前缀。此方法只返回指定列表中的公共前缀值,返回值可能是也可能不是有效路径,因为它通过逐个字符比较列表中的字符来检查公共前缀。
例如,考虑下面的路径列表:
list of paths common prefix
['/home/User/Photos', /home/User/Videos'] /home/User/ A valid path
['/usr/local/bin', '/usr/lib'] /usr/l Not a valid path
语法:os.path.commonprefix(list)
参数:
path:类路径对象列表。类路径对象是表示路径的字符串或字节对象。
返回类型:该方法返回一个表示指定列表中最长公共路径前缀的字符串值。
示例1
使用os.path.commonprefix()方法
# Python program to explain os.path.commonprefix() method
# importing os module
import os
# List of Paths
paths = ['/home/User/Desktop', '/home/User/Documents',
'/home/User/Downloads']
# Get the
# longest common path prefix
# in the specified list
prefix = os.path.commonprefix(paths)
# Print the
# longest common path prefix
# in the specified list
print("Longest common path prefix:", prefix)
# List of Paths
paths = ['/usr/local/bin', '/usr/bin']
# Get the
# longest common path prefix
# in the specified list
prefix = os.path.commonprefix(paths)
# Print the
# longest common path prefix
# in the specified list
print("Longest common path prefix:", prefix)
输出:
Longest common path prefix: /home/User/D
Longest common path prefix: /usr/
注意:如果指定的列表为空,os.path.commonprefix()方法将返回空字符串。