Sub topic 7
Working with paths using pathlib
This chapter assumes you can call open() and use the with statement, and that you know basic string methods. It covers the pathlib module, which represents file paths as objects instead of strings.
Why paths as objects
A path string such as "data/reports/summary.txt" is easy to get wrong. Windows separates folders with \, while Linux and macOS use /. Joining pieces with + also breaks when a slash is missing or doubled.
pathlib.Path solves this. It picks the right separator for the operating system and gives you methods for the common questions: what is the file name, which folder is it in, does it exist.
open() accepts a Path directly, so you can adopt pathlib without changing the code you already have.
Building paths with the / operator
The / operator joins path pieces. The left side must be a Path, and the right side can be a string or another Path.
from pathlib import Path
path = Path("data") / "reports" / "2026" / "summary.txt"
print(path) # data/reports/2026/summary.txt (backslashes on Windows)
print(path.name) # summary.txt
print(path.stem) # summary
print(path.suffix) # .txt
print(path.parent) # data/reports/2026
print(path.parts) # ('data', 'reports', '2026', 'summary.txt')These attributes only inspect the path text. Creating a Path does not touch the disk, so the file does not need to exist.
Creating a changed copy
Paths are immutable. Methods such as with_suffix() and with_name() return a new path and leave the original alone.
from pathlib import Path
report = Path("data/reports/summary.txt")
print(report.with_suffix(".csv")) # data/reports/summary.csv
print(report.with_name("archive.txt")) # data/reports/archive.txtChecking and creating things on disk
Some methods do talk to the file system. exists(), is_file() and is_dir() answer yes or no questions. mkdir() creates a folder.
from pathlib import Path
folder = Path("data") / "reports"
folder.mkdir(parents=True, exist_ok=True)
target = folder / "summary.txt"
with target.open("w", encoding="utf-8") as f:
f.write("totals\n")
print(target.exists(), target.is_file(), folder.is_dir()) # True True True
for item in sorted(folder.glob("*.txt")):
print(item.name) # summary.txtTwo arguments to mkdir() matter:
parents=Truecreates any missing parent folders, likemkdir -p. Without it, a missing parent raisesFileNotFoundError.exist_ok=Truestops an error when the folder already exists. Without it, a second run raisesFileExistsError.
glob("*.txt") yields the paths in a folder that match a pattern. rglob("*.txt") searches all subfolders as well. iterdir() yields every entry in one folder. None of these return results in a guaranteed order, so wrap them in sorted() when order matters.
Relative and absolute paths
A relative path such as Path("data") is resolved against the current working directory, which is the folder the program was started from. That folder is not necessarily the folder that holds your script, so the same code can find a file on one run and miss it on another.
Two tools help:
Path.cwd()returns the current working directory.path.resolve()returns the absolute path, with..parts and symbolic links resolved.
To locate files next to your script, build the path from the script's own location:
from pathlib import Path
base = Path(__file__).resolve().parent
config = base / "config.json"__file__ is not defined in an interactive session, so this works only in a script file.
Common mistakes
- Starting a join with a string.
"data" / "x"raisesTypeError. Begin withPath("data"). - Joining with an absolute path.
Path("data") / "/tmp/x"gives/tmp/x. An absolute right-hand side replaces everything on its left. - Assuming
exists()makes later code safe. The file can vanish between the check and theopen()call. HandleFileNotFoundErrortoo, as a later chapter shows. - Using
stemon multi-part extensions. Forarchive.tar.gz,suffixis.gzandstemisarchive.tar. Usesuffixesto get['.tar', '.gz'].
Exercise
A script runs Path("logs") / "app.log" and it works from the project folder but raises FileNotFoundError when started from your home folder. What is the cause, and how can you make the path independent of where the script is started?
Show answer
"logs" is a relative path, so it is resolved against the current working directory, which differs between the two runs. Build the path from the script's location instead: Path(__file__).resolve().parent / "logs" / "app.log".