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

  1. Use glob.glob("pattern") for simple matching.
  2. Use Path("dir").glob("**/*.py") for recursive searches.
  3. 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 for os.walk() plus string matching.
  • Escape literal square brackets in glob patterns because they are treated as character ranges.
  • Combine glob with os.path.getsize() or stat() to filter by file metadata.

Common issues

  • glob does 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.