Paths and folders: pathlib
🌍 In real life. A letter's address goes from big to small: country, city, road, house. A file's address works the same way: a folder, folders inside it, and finally the file. That address is called a path, like notes/day1.txt.
The idea in one sentence: pathlib.Path turns a path into an object you can join with /, take apart (name, extension, folder), check, read, write, and use to list a folder.
Its words:
- path: a file's or folder's address;
notes/day1.txtis relative, starting from the folder the program runs in - folder (directory): a box that holds files and other folders
- name, stem, suffix, parent: for
notes/day1.txt:day1.txt,day1,.txt, andnotes - glob: a pattern for many files at once:
*.txtmeans every name ending in.txt
Step by step:
from pathlib import Path, thenfolder = Path("notes")folder / "day1.txt"joins the parts with the right separator for the computer.exists()asks whether something is there;.read_text()and.write_text(text)read or write the whole file in one callfolder.glob("*.txt")gives every matching path in the folder
from pathlib import Path
folder = Path("notes")
p = folder / "day1.txt"
print(p, "|", p.name, p.stem, p.suffix, p.parent)
print(p.exists(), (folder / "day9.txt").exists())
print(p.read_text().splitlines())
for f in sorted(folder.glob("*.txt")):
print(f.name, "has", len(f.read_text().splitlines()), "lines")Why / and not +. Windows writes paths with a backslash (notes\day1.txt) and macOS and Linux with a slash. Gluing strings with + "/" bakes one of them in; folder / "day1.txt" lets Path pick the right one, so the same program works everywhere. The Python in this app runs like Linux, so it prints slashes. A Path also does the small jobs that are easy to get wrong by hand: the extension is whatever follows the last dot, and with_suffix(".bak") swaps only that.
Writing is one call too. write_text makes the file, or replaces what was in it, and gives back how many characters it wrote; mkdir(exist_ok=True) makes a folder unless it is already there:
from pathlib import Path
Path("backup").mkdir(exist_ok=True)
out = Path("backup") / "report.final.txt"
print(out.write_text("all good\n"))
print(out.read_text(), end="")
print(out.stem, out.suffix, out.with_suffix(".bak").name)Mistakes and edge cases.
- building paths with
+:"notes" + "day1.txt"givesnotesday1.txt; join with/ - a missing file:
read_text()on a path that doesn't exist stops with a FileNotFoundError; check.exists()first, or catch it (Chapter 18) write_textreplaces: it doesn't add to the end; to add, read the old text and write old + new, oropen(p, "a")(Lesson 20.2)- glob order isn't promised: the files can come in any order, so wrap it in
sorted()when the order matters - a slash at the start:
Path("notes") / "/day1.txt"throws awaynotes, because a path starting with/begins at the very top of the disk
Quiz
What does this print?
from pathlib import Path p = Path("photos") / "2026" / "trip.jpg" print(p.name, p.suffix, p.parent.name)What does this print?
from pathlib import Path p = Path("report.final.pdf") print(p.stem, p.suffix)What does this print?
from pathlib import Path p = Path("hello.txt") p.write_text("one") p.write_text("two") print(p.read_text())Why join paths with
/instead of+?- Path puts in the right separator for each computer
- / makes the file smaller
- + only works on numbers
The folder must stay "notes", as line 3 says. This should read notes/day1.txt but stops with a FileNotFoundError. Which line is wrong?
from pathlib import Path folder = "notes" p = Path(folder + "day1.txt") print(p.read_text())
Coding tasks
Write
count_txt(folder): how many.txtfiles are in the folderfolder(a string). Try it onnotes, which also holds a.mdfile.Write
line_counts(folder): a list of(file name, number of lines)pairs for every.txtfile in the folder, sorted by file name.Write
backup(path): copy the text of the file atpathinto a new file with the same name but the extension.bak(in the same folder), and return the new path as a string.