Use `os.walk` to process a directory and its subdirectories without writing the recursion yourself. Pass a starting path; the resulting iterator yields `(root, dirs, files)` for each directory. `root` is that directory’s path, while `dirs` and `files` are lists of names. Join `root` to a file name when you need its path. section 12.5 section 12.6.2
The optional arguments control the walk:
- `topdown=True` is the default: yield a directory before its descendants. Set it to `False` for bottom-up traversal. section 12.5
- During a top-down walk, remove names from `dirs` to prevent descent into those subdirectories. section 12.5
- `onerror` can handle errors from directory listing; such errors are otherwise ignored. Symbolic-link directories are not followed unless `followlinks=True`. section 12.5
import os
for root, dirs, files in os.walk(os.curdir):
print("{0} has {1} files".format(root, len(files)))
if ".config" in dirs: #1
dirs.remove(".config") #2
This loop counts files in each visited directory. Removing `.config` from `dirs` skips its subtree, not just its entry in the printed results. section 12.5
For file-level work, loop over `files` inside the walk and construct each path with `os.path.join(root, file)`. A size-total exercise filters for `.test` files, excludes symbolic links, and adds each selected file’s size. `Path.rglob` offers a `pathlib` alternative; the `os.walk` approach requires more explicit path handling. section 12.6.2 section 12.7
