Python中fnmatch模塊實現文件名匹配
fnmatch
模塊用于 文件名匹配,支持 Unix shell 風格的通配符(類似 glob
),但不匹配路徑,只匹配文件名。
與 glob
不同的是:
glob
是 在文件系統(tǒng)中搜索匹配的文件。fnmatch
只用于 匹配字符串模式,通常結合os.listdir()
使用。
1. fnmatch.fnmatch()
匹配 文件名 是否符合某個通配模式(不區(qū)分大小寫)。
import fnmatch # 直接匹配文件名 print(fnmatch.fnmatch("data.txt", "*.txt")) # True print(fnmatch.fnmatch("data.csv", "*.txt")) # False
2. fnmatch.fnmatchcase()
嚴格區(qū)分大小寫的匹配。
import fnmatch print(fnmatch.fnmatchcase("DATA.TXT", "*.txt")) # False (大小寫不同) print(fnmatch.fnmatchcase("data.TXT", "*.TXT")) # True
3. fnmatch.filter()
過濾列表,返回符合模式的文件名列表。
import fnmatch files = ["data.txt", "report.doc", "image.png", "notes.TXT"] # 過濾出所有 .txt 文件 txt_files = fnmatch.filter(files, "*.txt") print(txt_files) # ['data.txt']
4. fnmatch.translate()
將通配符模式轉換為正則表達式(regex)。
import fnmatch pattern = fnmatch.translate("*.txt") print(pattern)
輸出:
(?s:.*\.txt)\Z
可以用于 re.match()
進行更復雜的匹配。
5. 結合 os.listdir() 篩選文件
import os import fnmatch # 獲取當前目錄下的所有 .txt 文件 files = os.listdir(".") txt_files = fnmatch.filter(files, "*.txt") print(txt_files)
6. fnmatch vs glob
功能 | fnmatch | glob |
---|---|---|
主要用途 | 字符串匹配 | 文件查找 |
是否查找文件 | ? 僅匹配名稱 | ? 掃描目錄獲取匹配文件 |
常用方法 | fnmatch(), filter() | glob.glob(), rglob() |
7. 總結
fnmatch.fnmatch()
:匹配字符串(文件名)。fnmatch.fnmatchcase()
:大小寫敏感的匹配。fnmatch.filter()
:從列表中過濾符合模式的文件。fnmatch.translate()
:將通配符轉換為正則表達式。
適用于 字符串匹配,如 文件篩選、日志分析、路徑匹配 等。如果需要查找磁盤上的文件,建議使用 glob
或 os.listdir()
結合 fnmatch.filter()
。
到此這篇關于Python中fnmatch模塊實現文件名匹配的文章就介紹到這了,更多相關Python fnmatch模塊 內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
使用Python的Bottle框架寫一個簡單的服務接口的示例
這篇文章主要介紹了使用Python的Bottle框架寫一個簡單的服務接口的示例,基于Linux系統(tǒng)環(huán)境,需要的朋友可以參考下2015-08-08