Python Path.rglob
Walk a directory tree and select matching regular files.
A simple example
Path.rglob
- Start with Folder a contains b/c.txt
- Do this Visit descendants
- Result The walk reaches c.txt
Syntax
base.rglob("*.csv")
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyFind a receipt below the month folder
A treasurer has one receipt in a month folder and a note beside that folder. A recursive inventory should locate the nested CSV receipt while leaving the unrelated note out of its total.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
base = Path(folder)
month = base / "March"
month.mkdir()
(month / "dues.csv").touch()
(base / "notes.txt").touch()
print(sum(p.is_file() for p in base.rglob("*.csv")))
1
The month folder contributes one matching receipt below the top level.
Inventory class submissions
A teacher receives two top-level files and one file in a team folder. Count regular files throughout the folder tree, including its subfolders.
Inventory rehearsal parts
A school stores one score and two parts in a subfolder. Count regular files throughout the folder tree, including its subfolders.
What to watch for
Following symbolic links during recursion can revisit directories. Choose link handling deliberately.