Python

Walk Directory Tree (Filtered)

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Recursively yield every file under a directory matching a predicate. Built on pathlib.rglob; the predicate gives you precise control without listing the whole tree up front.
Python
Raw
from pathlib import Path
from typing import Callable, Iterator

def walk_files(
    root: str | Path,
    predicate: Callable[[Path], bool] = lambda _: True,
) -> Iterator[Path]:
    for p in Path(root).rglob("*"):
        if p.is_file() and predicate(p):
            yield p

# Every .py file under src/
for path in walk_files("src", lambda p: p.suffix == ".py"):
    print(path)

# All files modified in the last 24 hours
import time
recent_cutoff = time.time() - 86400
for path in walk_files(".", lambda p: p.stat().st_mtime >= recent_cutoff):
    print(path)
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.