Traverse Directories and Match Glob Patterns
Core idea
iterdir() yields immediate children; glob(pattern) selects matches; rglob(pattern) searches recursively. Filter for files when directory names could match, sort if presentation needs deterministic order, and keep the search rooted in a controlled directory.
from pathlib import Pathfrom tempfile import TemporaryDirectory
with TemporaryDirectory() as folder: root = Path(folder) for name in ["b.csv", "a.csv", "note.txt"]: (root / name).touch() print(sorted(p.name for p in root.glob("*.csv") if p.is_file()))The pattern selects CSV names; sorting removes order dependence.
Find nested files
from pathlib import Pathfrom tempfile import TemporaryDirectory
with TemporaryDirectory() as folder: root = Path(folder) (root / "sub").mkdir() (root / "sub" / "x.txt").touch() (root / "y.txt").touch() print(sorted(p.relative_to(root).as_posix() for p in root.rglob("*.txt")))Relative POSIX strings give a predictable display across operating systems.
Common mistake
Glob results are not promised to be sorted. Avoid unrestricted recursive walks over unknown trees; permissions, symlinks and filesystem changes affect results.
Practice
Create two subdirectories in a temporary root, add matching and nonmatching files and compare glob with rglob.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Directory selection
Check your understanding of directory traversal and glob.
What is printed?
from pathlib import Pathfrom tempfile import TemporaryDirectory
with TemporaryDirectory() as folder: root = Path(folder) (root / "d").mkdir() (root / "d" / "a.txt").touch() print(len(list(root.glob("*.txt"))), len(list(root.rglob("*.txt"))))What is printed?
from pathlib import Pathfrom tempfile import TemporaryDirectory
with TemporaryDirectory() as folder: root = Path(folder) (root / "a.txt").mkdir() print(sum(p.is_file() for p in root.glob("*.txt")))How can you make display order predictable?
Which method returns immediate children?