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=Trueis mandatory inglob.glob()/glob.iglob():- In the
globmodule,**behaves like a normal single-level*wildcard unless you explicitly passrecursive=True(glob.glob("src/**/*.py", recursive=True)). By contrast,Path.rglob("*.py")enables recursive matching automatically without needing**/orrecursive=True.
- In the
- Both
Path.rglob("*.py")andglob.glob("**/*.py", recursive=True)match files in the root directory itself too:**matches zero or more directory levels, so"**/*.py"matchesroot/app.py(depth 0) as well asroot/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+, passinclude_hidden=True(glob.glob("**/*.yml", recursive=True, include_hidden=True)), or usePath.rglob(".*")to match dotfiles explicitly.
- By default in Python $\le$ 3.10,
- Filter out matching directories (
if p.is_file()) and prune heavy folders (.git,node_modules,.venv):- Both
rglob()andglob()return directories if a folder name happens to match the pattern (e.g.,archive.tar/). Always checkp.is_file(). - Because
glob/rglobstill traverses into.git/ornode_modules/before filtering results, useos.walk()(mutatingdirs[:] = [d for d in dirs if d not in SKIP_DIRS]in-place) when searching massive repositories where skipping ignored subtrees avoids thousands of wastedstat()syscalls.
- Both
- Symlink loops (
follow_symlinks):- Starting in Python 3.13,
Path.rglob()andglob.glob()do not follow directory symlinks by default (follow_symlinks=Falsein Python $\ge$ 3.13, whereas Python $\le$ 3.12 followed them ingloband could loop infinitely on cyclic symlinks). Passfollow_symlinks=Truein Python 3.13+ only if you intentionally want to traverse symlinked subdirectories.
- Starting in Python 3.13,
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. |
You must log in or register to comment.
