Sub topic 1
Why pathlib: paths as objects instead of strings
Prerequisites
This chapter assumes you can write basic Python: functions, loops, f-strings, and print. You should also know what files, directories, and relative and absolute paths are on your operating system. You don't need to have used os.path before, but the comparison below is easier to follow if you have.
The problem with string paths
A path is often stored as a plain string such as "data/reports/summary.csv". A string has no idea it is a path. It doesn't know which separator your operating system uses, and it can't tell you its extension. Code that works with string paths ends up as a pile of helper calls and string concatenation.
The older approach uses the os.path module:
import os
report = os.path.join("data", "reports", "summary.csv")
print(os.path.dirname(report)) # data/reports
print(os.path.splitext(report)[1]) # .csvThis works, but each operation is a separate function, and every value is still a string.
Paths as objects
The pathlib module, part of the standard library since Python 3.4, represents a path as an object. The object has the operations you need as attributes and methods.
from pathlib import Path
report = Path("data") / "reports" / "summary.csv"
print(report.parent) # data/reports
print(report.suffix) # .csv
print(type(report)) # <class 'pathlib.PosixPath'> on Linux and macOSOn Windows the type is WindowsPath. When you write Path(...), Python picks the right flavor for the system you run on. You write the code once, and the separators are handled for you.
What you gain
- One place to look. Joining, splitting, checking existence, reading and listing all live on the same object.
- Readable joins. The
/operator replaces nestedos.path.joincalls. - Fewer string mistakes. You don't build paths with
+or slice off extensions by hand. - Immutability. A
Pathnever changes after creation. Methods such aswith_suffixreturn a new path, so passing a path to a function can't alter the caller's copy. - Platform awareness. Comparison and separator rules follow the operating system's conventions.
A worked example
Suppose you want to save a cleaned copy of a CSV next to the original, with _clean added to the file name. With strings, you split the extension, concatenate, and hope the file name has only one dot:
import os
source = "data/reports/summary.csv"
base, ext = os.path.splitext(source)
target = base + "_clean" + ext
print(target) # data/reports/summary_clean.csvWith pathlib, you ask the path for its parts and build a sibling:
from pathlib import Path
source = Path("data/reports/summary.csv")
target = source.with_name(f"{source.stem}_clean{source.suffix}")
print(target) # data/reports/summary_clean.csvEach piece has a name (stem, suffix), so the intent is visible. The next chapters cover these attributes and methods in detail.
Creating a path does not touch the disk
Creating a Path only builds an object in memory. The file or directory doesn't have to exist.
from pathlib import Path
ghost = Path("does/not/exist.txt")
print(ghost) # does/not/exist.txt
print(ghost.exists()) # FalseDisk access happens only when you call a method that needs it, such as exists(), read_text() or mkdir(). A later chapter separates "pure" paths, which never touch the disk, from "concrete" paths, which can.
Summary of the idea
Treat a path as a value with behavior, not as text. You build it once, ask it questions, and derive new paths from it. You convert to a string only when an older API requires one, which a later chapter covers.
Exercise
Given source = Path("notes/draft.txt"), which attribute gives you ".txt", and does calling source.with_suffix(".md") change source?
Show answer
The suffix attribute gives ".txt". with_suffix(".md") does not change source, because Path objects are immutable. It returns a new Path, notes/draft.md, and source stays notes/draft.txt.