Python os.path.commonprefix() 方法



Python 的os.path.commonprefix()方法用於查詢一組路徑字串中最長的公共字首。

  • 該方法從左到右逐字元比較給定的路徑。
  • 一旦遇到路徑之間不同的字元或到達最短路徑的末尾,它就停止比較。
  • 然後,該方法返回在提供的路徑中找到的最長的公共字首。
  • 如果沒有找到公共字首,則返回空字串。

語法

以下是 Python os.path.commonprefix() 方法的基本語法:

os.path.commonprefix(list_of_paths)

引數

此方法接受一個路徑字串列表(或任何可迭代物件)作為引數,用於查詢公共字首。

返回值

該方法返回一個字串,表示提供的路徑字串中的公共字首。

示例

在下面的示例中,我們使用 commonprefix() 方法查詢給定檔案路徑中最長的公共字首:

import os
paths = ["/home/lenovo/documents/file1.txt", "/home/lenovo/documents/file2.txt", "/home/lenovo/documents/file3.txt"]
prefix = os.path.commonprefix(paths)
print(prefix)    

輸出

獲得的輸出如下:

/home/lenovo/documents/file

示例

這裡,我們使用 commonprefix() 方法查詢檔案路徑和目錄路徑混合中最長的公共字首:

import os
paths = ["/path/to/folder1/file.txt", "/path/to/folder2", "/path/to/folder3/file.txt"]
prefix = os.path.commonprefix(paths)
print(prefix)    

輸出

以上程式碼的輸出如下:

/path/to/folder

示例

在這個例子中,我們使用 commonprefix() 方法查詢給定 URL 中的最長公共字首:

import os
urls = ["https://example.com/path1/page1.html", "https://example.com/path2/page2.html", "https://example.com/path3/page3.html"]
prefix = os.path.commonprefix(urls)
print(prefix)       

輸出

產生的結果如下所示:

https://example.com/path

示例

此示例顯示,如果任何路徑為空,則公共字首也將為空:

import os
paths = ["/path/to/folder1/file.txt", "", "/path/to/folder3/file.txt"]
prefix = os.path.commonprefix(paths)
print("The longest common prefix is:",prefix) 

輸出

我們得到如下所示的輸出:

The longest common prefix is: 
os_path_methods.htm
廣告