Sub topic 1
Why pathlib: paths as objects instead of strings
Prerequisites
This chapter assumes basic Python syntax, functions, loops, strings, and familiarity with files and directories. A path is the location of a file or directory, such as reports/summary.csv.
Why pathlib: paths as objects instead of strings
Python's pathlib module represents paths as objects. A Path object stores a path and provides operations for inspecting or changing it. This is clearer and safer than joining strings manually with / or \.
from pathlib import Path
report = Path("data") / "reports" / "2026" / "summary.csv"
print(report)The / operator joins path parts using the current operating system's separator. The expression does not create the file. It creates a description of where the file would be.
Pure paths and concrete paths
A concrete Path can interact with the file system. For example, it can check whether a file exists. A pure path only parses and combines path text. It never accesses the file system.
Use PureWindowsPath or PurePosixPath when you need to process a path format without depending on the operating system running Python.
from pathlib import Path, PureWindowsPath
actual = Path("data/report.csv")
windows = PureWindowsPath("C:/Users/ana/report.csv")
print(actual.name) # report.csv
print(windows.drive) # C:Taking paths apart: name, stem, suffix, parent, parts
Path properties expose useful pieces:
| Property | Example result |
|---|---|
| `name` | `report.final.tar.gz` |
| `stem` | `report.final.tar` |
| `suffix` | `.gz` |
| `parent` | `/home/ana/archive` |
| `parts` | `('/', 'home', 'ana', 'archive', 'report.final.tar.gz')` |
stem and suffix use only the final extension. Use suffixes when every extension matters.
from pathlib import Path
path = Path("/home/ana/archive/report.final.tar.gz")
print(path.name)
print(path.stem)
print(path.suffix)
print(path.suffixes)
print(path.parent)
print(path.parts)Exercise
What does Path("logs") / "today.txt" produce?
Show answer
It produces a new Path object describing logs/today.txt with the current system's separator.