Code

Paths Through the Archive

pathlib.Path is the modern way to work with file paths. A Path knows its own parts and joins with /, on every operating system.

from pathlib import Path

p = Path("maps") / "north" / "isle.map.txt"
print(p)          # maps/north/isle.map.txt
print(p.name)     # isle.map.txt
print(p.stem)     # isle.map   (name minus last suffix)
print(p.suffix)   # .txt
print(p.parent)   # maps/north

Handy methods:

  • p.parent.mkdir(parents=True, exist_ok=True) makes the folder (and any missing parents), and is fine if it already exists.
  • p.write_text("hi", encoding="utf-8") writes a whole file in one call. It opens, writes and closes for you.
  • p.read_text(encoding="utf-8") reads a whole file the same way.
  • p.exists(), p.is_dir(), p.is_file() check what's there.
  • Path("maps").glob("*.txt") finds matching files in a folder.

Assignment

  1. Complete save_note(folder, title, text): create folder (with any missing parents), write text to <title>.txt inside it, and return the Path of the new file.
  2. Complete note_titles(folder): return a sorted list of the stems of every .txt file in folder. If the folder doesn't exist, return [].