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.
More on OS, filesystem, subprocess & CLIs
`os.path` vs `pathlib`: which do you use and why?BeginnerHow do you read environment variables safely?BeginnerWhat does `shutil` give you that `os` does not?BeginnerHow do you run an external command correctly with `subprocess`?BeginnerWhy is `shell=True` dangerous, and when is it acceptable?IntermediateHow do you handle a failed command and show useful output?Intermediate