Code

Survey the Archive

Pip has a new job in the Guild's Clockwork Workshop: teaching Python to do boring chores. Rule one for any file chore: look before you touch. So first we just list what's there.

Finding files with pathlib

Path.rglob("*") walks a folder and every folder inside it. It gives you folders and files, so keep only the files with .is_file().

from pathlib import Path

root = Path("archive")
for p in root.rglob("*"):
    if p.is_file():
        print(p.relative_to(root).as_posix())
  • relative_to(root) drops the archive/ part, so archive/maps/north.txt becomes maps/north.txt.
  • as_posix() always uses /, even on Windows (which shows \). Your report looks the same on every computer.
  • The disk can hand back files in any order. Sort the list so every run gives the same result.

A sorted list of files like this is called a manifest.

On your computer

Here, files live on a pretend disk inside your browser. The setup block at the top builds a sample folder each time you press Run. On a real computer the same code reads real folders, for example Path.home() / "Documents". It only reads, so it's safe to try.

Assignment

  1. Complete survey(root). Return a sorted list of every file under root, at any depth, as /-separated paths relative to root (strings like "maps/north.txt"). Skip folders.
  2. Complete suffix_counts(root). Return a dict that counts files by their lowercase suffix, like {".txt": 2, ".csv": 1}. Files with no suffix count under "". (p.suffix gives the suffix.)
  3. Both functions must work when root is a string or a Path.