Python 中的 fnmatch 模組
Vaibhav Vaibhav
2023年10月10日
Python
Python Module
在處理檔案和檔案系統時,經常需要從一堆檔案中找到幾個檔案。如果手動執行,從一堆檔案中查詢所需檔案將花費很長時間。
因此,作業系統和程式語言提供了用於動態查詢所需檔案的實用程式。這些實用程式傾向於以檔名為目標,並嘗試在模式匹配的幫助下找到必要的檔案。
在諸如 macOS 和 Linux 等基於 UNIX 的作業系統中,可以藉助 Python 程式語言中的 fnmatch 庫來定位檔案。
本文將學習如何使用 Python 的 fnmatch 庫執行模式匹配。
Python 中的 fnmatch 模組
fnmatch 模組用於匹配 UNIX 作業系統 shell 樣式的萬用字元。請注意,這些樣式不是 regex 或 regular 表示式。
以下是 UNIX shell-style wildcards 中使用的特殊字元:
| 模式 | 操作 |
|---|---|
* |
匹配一切 |
? |
匹配單個字元 |
[sequence] |
匹配序列中的任何字元 |
[!sequence] |
匹配任何字元,而不是按順序 |
fnmatch 庫有以下方法:
fnmatch.fnmatch(filename, pattern)是fnmatch()方法,將檔名與指定模式匹配。如果模式匹配,則返回True;否則,假。請注意,此方法不區分大小寫,並且在os.path.normcase()方法的幫助下,兩個引數都被標準化為小寫。fnmatch.fnmatchcase(filename, pattern)- 與fnmatch()方法非常相似,但它區分大小寫並且不對引數應用os.path.normcase()方法。fnmatch.filter(names, pattern)建立與指定模式匹配的檔名列表。此方法類似於遍歷所有檔名並執行fnmatch()方法,但實現效率更高。fnmatch.translate(pattern)在re.match()方法的幫助下將 shell 樣式模式轉換為正規表示式或正規表示式。
現在我們已經瞭解了一些理論,讓我們在相關示例的幫助下了解如何實際使用這個庫。
該示例過濾所有以 .html 副檔名結尾的檔案。
import os
import fnmatch
for file in os.listdir("."):
if fnmatch.fnmatch(file, "*.html"):
print(file)
輸出:
<files with ".html" extension in the current working directory>
上面的 Python 程式碼首先在 os.listdir() 方法的幫助下讀取當前工作目錄中的所有檔案。接下來,它遍歷所有檔案並使用 fnmatch() 方法檢查它們是否是 HTML 檔案。
這裡,*.html 模式匹配所有以 .html 結尾的檔案。這裡,* 是指檔名中的任意數量的字元。
讓我們看另一個過濾所有以 hello 開頭並以 .js 結尾的檔案的示例。請參閱以下 Python 程式碼。
import os
import fnmatch
for file in os.listdir("."):
if fnmatch.fnmatch(file, "hello*.js"):
print(file)
輸出:
<files with filenames of type "hello*.js" in the current working directory>
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Vaibhav Vaibhav
