liveBook · Manning

Os.walk

As explained in The Quick Python Book, Fourth Edition

os.walk is a Python standard-library function that recursively traverses a directory tree and yields each directory's path, subdirectories, and files.

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

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains yielded values, traversal order, pruning, error handling, and symbolic-link options, then applies the iterator in filesystem exercises.
Examples
Uses a `.config`-pruning file count and scripts that total or move selected `.test` files.
What it assumes
Assumes familiarity with Python loops and paths; teaches the traversal-specific return values and controls.
What you can do after
Apply it via Python’s `os` module to traverse a subtree, skip selected directories, and process matching files.
How it connects
Connects directory traversal to `os.path.join`, symbolic links, file-size queries, and `Path.rglob`.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.