How do I find files with glob pattern matching in Python?
· Category: Python Programming
Short answer
The glob module and pathlib.Path.glob() let you find files using shell-style wildcards like * and **. fnmatch filters filenames against patterns, while pathlib offers an object-oriented approach.
Steps
- Use
glob.glob("pattern")for simple matching. - Use
Path("dir").glob("**/*.py")for recursive searches. - Use
fnmatch.filter(names, "*.txt")to filter an existing list.
import glob
from pathlib import Path
# Simple glob
print(glob.glob("*.py"))
# Recursive pathlib
for py_file in Path("src").rglob("*.py"):
print(py_file)
# fnmatch
import fnmatch
names = ["data.csv", "report.txt", "image.png"]
print(fnmatch.filter(names, "*.csv"))
Tips
Path.rglob()is recursive by default and is the modern replacement foros.walk()plus string matching.- Escape literal square brackets in glob patterns because they are treated as character ranges.
- Combine
globwithos.path.getsize()orstat()to filter by file metadata.
Common issues
globdoes not match hidden files (starting with.) unless the pattern explicitly includes the dot.- Case sensitivity depends on the operating system filesystem.
- Very deep directory trees can be slow with recursive globs; consider
os.scandir()for performance-critical traversal.