Interview Prep/Python for DevOps/OS, filesystem, subprocess & CLIs

How do you walk a directory tree and find files?

BeginnerConceptOS, filesystem, subprocess & CLIs
Answer
from pathlib import Path
big = [p for p in Path("/var/log").rglob("*.log") if p.is_file() and p.stat().st_size > 100 * 2**20]

import os
for root, dirs, files in os.walk("/etc"):
    dirs[:] = [d for d in dirs if not d.startswith(".")]   # prune in place
    for f in files:
        ...

os.walk lets you prune directories as you go, which matters on huge trees; rglob is shorter. Catch PermissionError when walking system paths as a non-root user.

All Python for DevOps questions Roadmap: Python for automation

More on OS, filesystem, subprocess & CLIs