Python 如何查詢具有特定副檔名的檔案
Jinku Hu 2023年1月30日 Python Python File
-
glob.glob
查詢具有特定副檔名的檔案的方法 -
os.listdir()
查詢具有特定副檔名的檔案的方法 -
pathlib.glob
查詢具有特定副檔名的檔案的方法 - 在 Python 中的目錄及其子目錄中查詢具有特定副檔名的檔案
-
pathlib
遞迴地搜尋模組檔案

本文介紹了在 Python 中查詢具有特定副檔名的檔案的不同方法。
glob.glob
查詢具有特定副檔名的檔案的方法
我們可以使用 Python 中的 glob.glob
模組來查詢具有特定副檔名的檔案。
import glob targetPattern = r"C:\Test\*.txt" glob.glob(targetPattern)
上面的程式碼演示瞭如何列出目錄 C:\Test
中具有副檔名位 txt
的檔案。
os.listdir()
查詢具有特定副檔名的檔案的方法
os.listdir()
函式列出給定目錄中的所有檔案,但不包含檔案路徑資訊。你可以使用 str.endswith()
函式提取具有特定副檔名的檔案。
>>> import os >>> fileDir = r"C:\Test" >>> fileExt = r".txt" >>> [_ for _ in os.listdir(fileDir) if _.endswith(fileExt)] ['test.txt', 'test1.txt']
你需要使用 os.path.join()
函式構造完整路徑。
>>> import os >>> fileDir = r"C:\Test" >>> fileExt = r".txt" >>> [os.path.join(fileDir, _) for _ in os.listdir(fileDir) if _.endswith(fileExt)] ['C:\\Test\\test.txt', 'C:\\Test\\test1.txt']
pathlib.glob
查詢具有特定副檔名的檔案的方法
Python 3.4 中引入了 pathlib 模組,提供了物件導向的檔案系統路徑。它提供兩種樣式:Windows OS 中的 Windows 路徑和 Unix 類系統中的 POSIX 路徑。
>>> import pathlib >>> fileDir = r"C:\Test" >>> fileExt = r"*.txt" >>> list(pathlib.Path(fileDir).glob(fileExt)) [WindowsPath('C:/Test/test.txt'), WindowsPath('C:/Test/test1.txt')]
結果用 WindowsPath
表示,你可以通過 str()
函式將結果轉換為字串表示形式,例如
>>> [str(_) for _ in pathlib.Path(fileDir).glob(fileExt)] ['C:\\Test\\test.txt', 'C:\\Test\\test.txt']
在 Python 中的目錄及其子目錄中查詢具有特定副檔名的檔案
模式 C:\Test\*.txt
僅在 C:\Test
目錄中查詢 txt
檔案,而不在其子目錄中查詢檔案。如果你還想在子目錄中查詢檔案 txt
,則可以對模式做一些修改。
import glob targetPattern = r"C:\Test\**\*.txt" glob.glob(targetPattern)
Test
和\*.txt
之間的萬用字元**
表示在目錄及其子目錄中查詢 txt
檔案。
pathlib
遞迴地搜尋模組檔案
跟在 glob.glob
新增**
來遞迴搜尋檔案類似,你還可以在 pathlib.Path.glob
方法中新增**
來遞迴查詢特定副檔名的檔案。
>>> import pathlib >>> fileDir = r"C:\Test" >>> fileExt = r"**\*.txt" >>> list(pathlib.Path(fileDir).glob(fileExt)) [WindowsPath('C:/Test/test.txt'), WindowsPath('C:/Test/test1.txt'), WindowsPath('C:/Test/sub/test1.txt')]
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Jinku Hu