fnmatch Filters Filenames By Patterns
fnmatch.filter matches shell-style patterns against filename lists, and fnmatchcase opts out of the platform case-insensitivity that fnmatch applies.
Code
import fnmatch
names = ["report-2026.csv", "report-2025.csv", "summary.csv", "log.txt"]
# shell 通配符过滤文件名
print(sorted(fnmatch.filter(names, "report-*.csv")))
print(fnmatch.filter(names, "*.csv"))
# ? 匹配单个字符
print(fnmatch.fnmatch("report-2026.csv", "report-202?.csv"))
# fnmatch 跟随平台大小写规则;fnmatchcase 恒定严格
print(fnmatch.fnmatchcase("LOG.TXT", "*.txt"), fnmatch.fnmatch("LOG.TXT", "*.txt"))
for pattern in ("*.txt", "*.csv"):
print(pattern, "=>", fnmatch.filter(names, pattern))How it works
Iteration happens inside for pattern in ("*.txt", "*.csv") — everything outside it runs once.
Module-level bindings hold the data — names — with no function scope in between.
What to watch for
- Nothing to install:
fnmatchships with the Python standard library.
Statements that matter
for pattern in ("*.txt", "*.csv"):
print(pattern, "=>", fnmatch.filter(names, pattern))
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free. Its state lives in module-level bindings: `names`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.