Python os.path.commonprefix() - 获取路径列表中的最长公共路径前缀

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()方法将返回空字符串。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程