Python| os.path.commonprefix() 方法
Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。 os.path模块是Python中OS 模块的子模块,用于常见的路径名操作。
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
Syntax: os.path.commonprefix(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 path prefix in specified list.
代码 #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()
方法将返回一个空字符串。
参考: https://docs。 Python.org/3/library/os.path.html