
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
- Complete
save_note(folder, title, text): createfolder(with any missing parents), writetextto<title>.txtinside it, and return thePathof the new file. - Complete
note_titles(folder): return a sorted list of the stems of every.txtfile infolder. If the folder doesn't exist, return[].
- Complete
save_note(folder, title, text): createfolder(with any missing parents), writetextto<title>.txtinside it, and return thePathof the new file. - Complete
note_titles(folder): return a sorted list of the stems of every.txtfile infolder. If the folder doesn't exist, return[].
main.py Python sleeping
Press Run to try your code, then Check to test it.