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.

PythonCli Tooling

Code

pythonsnippet
15 lines
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: fnmatch ships with the Python standard library.

Statements that matter

for pattern in ("*.txt", "*.csv"):
    print(pattern, "=>", fnmatch.filter(names, pattern))

Interactive Tools for This Topic

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`.