当前位置: 代码网 > it编程>前端脚本>Python > Python中fnmatch模块实现文件名匹配

Python中fnmatch模块实现文件名匹配

2025年04月29日 Python 我要评论
fnmatch模块用于文件名匹配,支持unix shell 风格的通配符(类似glob),但不匹配路径,只匹配文件名。与glob不同的是:glob是在文件系统中搜索匹配的文件。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

功能fnmatchglob
主要用途字符串匹配文件查找
是否查找文件❌ 仅匹配名称✅ 扫描目录获取匹配文件
常用方法fnmatch(), filter()glob.glob(), rglob()

7. 总结

  • fnmatch.fnmatch():匹配字符串(文件名)。
  • fnmatch.fnmatchcase():大小写敏感的匹配。
  • fnmatch.filter():从列表中过滤符合模式的文件。
  • fnmatch.translate():将通配符转换为正则表达式。

适用于 字符串匹配,如 文件筛选、日志分析、路径匹配 等。如果需要查找磁盘上的文件,建议使用 glob 或 os.listdir() 结合 fnmatch.filter()

到此这篇关于python中fnmatch模块实现文件名匹配的文章就介绍到这了,更多相关python fnmatch模块 内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com