File system · 2 / 15 Theory

Walking folders and searching for files

There are three usual ways to walk a folder: iterdir() (first level only), glob / rglob (with patterns) and os.walk (the whole tree, level by level).

import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp:       # temporary folder deleted on exit
    base = Path(tmp)
    (base / "src" / "util").mkdir(parents=True)  # also creates the intermediate folders
    (base / "src" / "main.py").write_text("print('hello')\n")
    (base / "src" / "util" / "tools.py").write_text("x = 1\n")
    (base / "README.md").write_text("# Project\n")

    print(sorted(p.name for p in base.iterdir()))              # ['README.md', 'src']
    print(sorted(p.relative_to(base).as_posix() for p in base.rglob("*.py")))
    # ['src/main.py', 'src/util/tools.py']
    print(sorted(p.name for p in (base / "src").glob("*")))    # ['main.py', 'util']

    import os
    for folder, subfolders, files in os.walk(base):       # classic walk
        subfolders.sort()                                     # fixes the visiting order
        nivel = Path(folder).relative_to(base).as_posix()
        print(nivel, sorted(files))
    # . ['README.md']
    # src ['main.py']
    # src/util ['tools.py']
PatternMatches
*any sequence of characters (without crossing folders)
?a single character
[0-9]one character from the range
**any number of subfolders (with glob("**/*.py") or with rglob)
  • The order is not guaranteed: iterdir, glob and os.walk return entries in the system’s order. If the result matters, sort it with sorted(...).
  • rglob("*") also includes folders; filter with is_file() if you only want files.
  • Walking a folder that does not exist does not fail: it just returns nothing (but iterdir() does raise FileNotFoundError).
  • To show a tree, a recursive function that is called with each subfolder and increases the indentation is the simplest solution.

You practice it in List a folder, Count files by extension, Directory tree and Search with patterns.