在 Python 中獲取副檔名
本教程將介紹如何在 Python 中從檔名中獲取副檔名。
在 Python 中使用 os.path 模組從檔案中提取副檔名
Python 的模組 os.path 預製了有用的實用函式來操作作業系統的檔案路徑,包括開啟、儲存和更新,以及從檔案路徑中獲取資訊。
我們將使用這個模組來獲取 Python 中的副檔名。
os.path 有一個函式 splitext(),用來分割給定檔案路徑的根和副檔名。該函式返回一個包含根字串和擴充套件字串的元組。
讓我們提供一個帶有 docx 副檔名的檔案路徑示例。
/Users/user/Documents/sampledoc.docx
預期的輸出應該是副檔名 .docx。
宣告兩個獨立的變數 extension 和 root 來捕獲 splitext() 的結果。
import os
path = "/Users/user/Documents/sampledoc.docx"
root, extension = os.path.splitext(path)
print("Root:", root)
print("extension:", extension)
輸出:
Root: /Users/user/Documents/sampledoc
Extension: .docx
副檔名現在已經從根檔案路徑成功返回。
在 Python 中使用 pathlib 模組從檔案中提取副檔名
pathlib 是一個 Python 模組,它包含代表檔案路徑的類,併為這些類實現實用函式和常量。
pathlib.Path() 接受一個路徑字串作為引數並返回一個新的 Path 物件。
pathlib.Path 物件有屬性 suffix,返回檔案擴充套件資訊。
import pathlib
path = pathlib.Path("/Users/user/Documents/sampledoc.docx")
print("Parent:", path.parent)
print("Filename:", path.name)
print("Extension:", path.suffix)
除了根目錄外,我們還可以通過簡單呼叫 Path 物件內的屬性 parent 和 name 來獲取給定檔案路徑的父檔案路徑和實際檔名。
輸出:
Parent: /Users/user/Documents
Filename: sampledoc.docx
Extension: .docx
如果副檔名是 .tar.gz 或 .tar.bz2 呢?
pathlib 還提供了一個屬性,用於處理有多個字尾的檔案。Path 物件中的屬性 suffixes 是一個包含所有給定檔案字尾的列表。如果我們使用上面的例子並列印出 suffixes 屬性。
import pathlib
path = pathlib.Path("/Users/user/Documents/sampledoc.docx")
print("Suffix(es):", path.suffixes)
輸出:
Suffix(es): ['.docx']
所以即使只有一個字尾,輸出的結果也會是一個列表。
現在試試用 .tar.gz 副檔名的例子。要將列表轉換為單字串,可以在一個空字串上使用 join() 函式,並接受 suffixes 屬性作為引數。
import pathlib
path = pathlib.Path("/Users/user/Documents/app_sample.tar.gz")
print("Parent:", path.parent)
print("Filename:", path.name)
print("Extension:", "".join(path.suffixes))
輸出:
Parent: /Users/user/Documents
Filename: app_sample.tar.gz
Extension: .tar.gz
現在顯示的是實際的副檔名,而不是一個列表。
總之,os 和 pathlib 這兩個模組提供了在 Python 中從檔案路徑中獲取副檔名的方便方法。
os 模組有一個函式 splitext,用於將根和檔名從副檔名中分離出來。pathlib 建立一個 Path 物件,並簡單地將副檔名儲存在 suffix 屬性中。
如果你預計一個檔案中有多個副檔名,最好使用 pathlib,因為它使用 suffixes 屬性為多個副檔名提供了輕鬆的支援。
Skilled in Python, Java, Spring Boot, AngularJS, and Agile Methodologies. Strong engineering professional with a passion for development and always seeking opportunities for personal and career growth. A Technical Writer writing about comprehensive how-to articles, environment set-ups, and technical walkthroughs. Specializes in writing Python, Java, Spring, and SQL articles.
LinkedIn