How do you recursively find all matching files in subdirectories using glob in Python? | A1Lab@MZeeshanM to PythonEnglish • 2 days ago

How do you recursively find all matching files in subdirectories using glob in Python?

message-square
0

Use Path(root_dir).rglob("*.py") from the built-in pathlib module (or glob.glob("**/*.py", root_dir=root_dir, recursive=True) from the glob module) to recursively search a directory and all nested subdirectories for matching filenames—filtering with .is_file() when directories might share the extension (e.g., a folder named backup.py/).

Basic Example

import glob
from pathlib import Path

# 1. Recommended: `pathlib.Path.rglob()` (returns a lazy generator of `Path` objects)
py_files = sorted(p for p in Path("src").rglob("*.py") if p.is_file())
for path in py_files:
    print(path)

# 2. Using the `glob` module directly (`recursive=True` is mandatory for `**`):
csv_files = glob.glob("**/*.csv", root_dir="data", recursive=True)
print(csv_files)

# 3. Lazy iterator version in `glob` for huge directory trees (`iglob`):
for log_path in glob.iglob("logs/**/*.log", recursive=True):
    print(log_path)

Key Details & Edge Cases

  • recursive=True is mandatory in glob.glob() / glob.iglob():
    • In the glob module, ** behaves like a normal single-level * wildcard unless you explicitly pass recursive=True (glob.glob("src/**/*.py", recursive=True)). By contrast, Path.rglob("*.py") enables recursive matching automatically without needing **/ or recursive=True.
  • Both Path.rglob("*.py") and glob.glob("**/*.py", recursive=True) match files in the root directory itself too:
    • ** matches zero or more directory levels, so "**/*.py" matches root/app.py (depth 0) as well as root/sub/pkg/utils.py (depth 2+).
  • Hidden files and dotfiles (.env, .gitignore, .hidden/file.txt):
    • By default in Python $\le$ 3.10, * and ** skip files and directories starting with a leading dot (.). In Python 3.11+, pass include_hidden=True (glob.glob("**/*.yml", recursive=True, include_hidden=True)), or use Path.rglob(".*") to match dotfiles explicitly.
  • Filter out matching directories (if p.is_file()) and prune heavy folders (.git, node_modules, .venv):
    • Both rglob() and glob() return directories if a folder name happens to match the pattern (e.g., archive.tar/). Always check p.is_file().
    • Because glob/rglob still traverses into .git/ or node_modules/ before filtering results, use os.walk() (mutating dirs[:] = [d for d in dirs if d not in SKIP_DIRS] in-place) when searching massive repositories where skipping ignored subtrees avoids thousands of wasted stat() syscalls.
  • Symlink loops (follow_symlinks):
    • Starting in Python 3.13, Path.rglob() and glob.glob() do not follow directory symlinks by default (follow_symlinks=False in Python $\ge$ 3.13, whereas Python $\le$ 3.12 followed them in glob and could loop infinitely on cyclic symlinks). Pass follow_symlinks=True in Python 3.13+ only if you intentionally want to traverse symlinked subdirectories.

Comparison of Recursive File-Matching Methods in Python

Method Return Type Requires recursive=True? Supports Pruning Folders (.git, .venv) Mid-Traversal? Best Used When
Path(root).rglob("*.ext") (Recommended) Generator of pathlib.Path objects No (always recursive) No (filters after traversal) Clean, idiomatic, cross-platform recursive searches in modern Python 3 codebases.
glob.glob("**/*.ext", root_dir=..., recursive=True) list[str] (relative to root_dir) Yes No When you specifically need relative string paths (root_dir= requires Python 3.10+) or include_hidden=True (Python 3.11+).
glob.iglob("**/*.ext", recursive=True) Generator of str paths Yes No Streaming millions of matching string paths lazily with $O(1)$ memory overhead.
os.walk(root) + fnmatch.fnmatch() Generator of (dirpath, dirnames, filenames) N/A Yes (mutate dirnames[:] in-place) Large repositories or monorepos where skipping .git, node_modules, or .venv dramatically speeds up traversal.