
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 thearchive/part, soarchive/maps/north.txtbecomesmaps/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
- Complete
survey(root). Return a sorted list of every file underroot, at any depth, as/-separated paths relative toroot(strings like"maps/north.txt"). Skip folders. - 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.suffixgives the suffix.) - Both functions must work when
rootis a string or aPath.
- Complete
survey(root). Return a sorted list of every file underroot, at any depth, as/-separated paths relative toroot(strings like"maps/north.txt"). Skip folders. - 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.suffixgives the suffix.) - Both functions must work when
rootis a string or aPath.
main.py Python sleeping
Press Run to try your code, then Check to test it.