PythiloLesson 26 of 30 · progress kept in this browser

Paths and folders

pathlib.Path joins path parts with /, so the same code works on every system. A Path is only a name until you ask it to touch the disk.

from pathlib import Path

folder = Path("notes")
folder.mkdir(exist_ok=True)
a = folder / "a.txt"
a.write_text("hi", encoding="utf-8")
b = folder / "b.md"
b.write_text("yo", encoding="utf-8")

print(a.name, a.stem, a.suffix)
print(a.parent)  # notes
txt = folder.glob("*.txt")
print(sorted(p.name for p in txt))
  • mkdir(parents=True, exist_ok=True) creates any missing parent folders and does not fail when the folder already exists.
  • iterdir() lists a folder's entries. glob("*.txt") matches names, and rglob also searches subfolders.
  • is_file() and is_dir() tell entries apart, and exists() checks either.
  • a.with_suffix(".bak") is a new path with another extension.

The order of iterdir and glob results is not defined, so sort them before you depend on it.

Your task

Write save_note(folder, name, text) that creates folder and any missing parents, writes text to the file name + ".txt" inside it, and returns the path. Write list_notes(folder) returning the sorted stems of the .txt files in folder, or [] if the folder does not exist.

Next: JSON files