Python中的OS模塊提供了與操作係統進行交互的函數。操作係統屬於Python的標準實用程序模塊。該模塊提供了使用依賴於操作係統的函數的便攜式方法。 os.path模塊是Python中OS模塊的子模塊,用於通用路徑名操作。
os.path.commonpath()
Python中的方法用於獲取路徑列表中最長的通用sub-path。如果指定的路徑列表包含絕對路徑和相對路徑,或者為空,則此方法引發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:path-like對象的列表。 path-like對象是表示路徑的字符串或字節對象。
返回類型:此方法返回一個字符串值,該字符串值表示指定列表中最長的公用sub-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。
參考: https://docs.python.org/3/library/os.path.html
相關用法
- Python os.dup()用法及代碼示例
- Python next()用法及代碼示例
- Python set()用法及代碼示例
- Python object()用法及代碼示例
- Python bytes()用法及代碼示例
- Python os.times()用法及代碼示例
- Python os.chmod用法及代碼示例
- Python hash()用法及代碼示例
- Python os.ftruncate()用法及代碼示例
- Python os.truncate()用法及代碼示例
- Python os.fsdecode()用法及代碼示例
- Python dict pop()用法及代碼示例
- Python os.abort()用法及代碼示例
- Python os.WEXITSTATUS()用法及代碼示例
注:本文由純淨天空篩選整理自ihritik大神的英文原創作品 Python | os.path.commonpath() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。