Python中fnmatch模块实现文件名匹配
作者:彬彬侠
fnmatch模块用于文件名匹配,支持 Unix shell风格的通配符,本文主要介绍了Python中fnmatch模块实现文件名匹配,具有一定的参考价值,感兴趣的可以了解一下
fnmatch 模块用于 文件名匹配,支持 Unix shell 风格的通配符(类似 glob),但不匹配路径,只匹配文件名。
与 glob 不同的是:
glob是 在文件系统中搜索匹配的文件。fnmatch只用于 匹配字符串模式,通常结合os.listdir()使用。
1. fnmatch.fnmatch()
匹配 文件名 是否符合某个通配模式(不区分大小写)。
import fnmatch
# 直接匹配文件名
print(fnmatch.fnmatch("data.txt", "*.txt")) # True
print(fnmatch.fnmatch("data.csv", "*.txt")) # False
2. fnmatch.fnmatchcase()
严格区分大小写的匹配。
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模块 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
