Python os.path.commonpath() - 获取路径列表中最长的公共子路径

Python os.path.commonpath()

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               

语法:os.path.commonpath(list)

参数:

path:类路径对象列表。类路径对象是表示路径的字符串或字节对象。

返回类型:该方法返回一个表示指定列表中最长公共子路径的字符串值。

示例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错误。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程