Sub topic 1
Why pathlib: paths as objects instead of strings
Prerequisites
This chapter assumes you can write Python functions and loops and use print and basic string operations. It also assumes you know what files, directories, and absolute and relative paths are on your operating system. You need Python 3.6 or newer. The examples use Python 3.12 behavior.
The problem with paths as strings
A file path is structured data. It has a root, a sequence of directory names, and a final name that may carry an extension. Older Python code stores that structure in a plain str. The string itself knows nothing about separators, extensions, or the operating system, so every operation needs a helper function or manual slicing.
Here is a typical string-based approach:
import os
base = "data"
report = base + "/" + "reports" + "/" + "summary.csv"
print(report)
# Take it apart with string tricks
name = report.split("/")[-1]
ext = name.rsplit(".", 1)[-1]
print(name, ext)This code works on Linux and macOS. On Windows the hard-coded / often still works, but paths you receive from other sources use \, and your split("/") will silently return the whole path. The code also breaks if a name has no dot, because rsplit then returns the full name as the "extension".
The os.path module fixes some of this:
import os
report = os.path.join("data", "reports", "summary.csv")
folder, filename = os.path.split(report)
stem, ext = os.path.splitext(filename)
print(folder, stem, ext)This is correct and portable. The cost is readability. The operations live in a separate module, the functions take and return strings, and a nested call such as os.path.dirname(os.path.dirname(os.path.abspath(__file__))) reads inside out.
What pathlib offers
The pathlib module, added in Python 3.4, represents a path as an object. The object stores the parsed path and offers methods and properties for the operations you would otherwise spread across os, os.path, glob, shutil, and the built-in open.
from pathlib import Path
report = Path("data") / "reports" / "summary.csv"
print(report) # data/reports/summary.csv on POSIX systems
print(report.name) # summary.csv
print(report.suffix) # .csv
print(report.parent) # data/reportsThe same task now reads left to right. Each piece of information is an attribute of the object, and the object picks the correct separator for the operating system it runs on.
Comparing the two styles
| Task | String / `os.path` | `pathlib` |
|---|---|---|
| Join segments | `os.path.join(a, b)` | `Path(a) / b` |
| Final component | `os.path.basename(p)` | `p.name` |
| Parent directory | `os.path.dirname(p)` | `p.parent` |
| Extension | `os.path.splitext(p)[1]` | `p.suffix` |
| Does it exist? | `os.path.exists(p)` | `p.exists()` |
| Read a text file | `open(p).read()` | `p.read_text()` |
| List matching files | `glob.glob(pattern)` | `p.glob(pattern)` |
How a Path object behaves
Three properties of Path explain most of its design.
- Immutable. A
Pathnever changes after you create it. Methods such aswith_suffixreturn a new object. You can use paths as dictionary keys and share them between functions without defensive copies. - Normalized on creation.
Pathcollapses repeated separators and removes.segments.Path("a//b/./c")becomesa/b/c. It does not remove.., because doing so could change which file the path refers to when symbolic links are involved. - Comparable and sortable. Two paths with the same parts compare equal, and paths sort by their parts. On Windows, comparison ignores case, matching the file system.
from pathlib import Path
a = Path("a//b/./c")
print(a) # a/b/c
print(a == Path("a/b/c")) # True
print(Path("a/../b")) # a/../b (".." is kept)
print(len({a, Path("a/b/c")})) # 1, because paths are hashableCreating a Path
Path(...) accepts one or more strings or other path objects. With no arguments it gives the current directory, Path(".").
from pathlib import Path
print(Path("data", "reports", "summary.csv")) # data/reports/summary.csv
print(Path()) # .
print(Path("data") / Path("raw")) # data/rawWhen you construct Path, Python returns PosixPath on Linux and macOS and WindowsPath on Windows. You almost never name these classes yourself.
from pathlib import Path
p = Path("example.txt")
print(type(p).__name__) # PosixPath or WindowsPath, depending on your systemA worked comparison
The following task is small but realistic. Given a directory of reports, create a backup path for each .csv file by changing its folder and adding a .bak suffix. The string version:
import glob
import os
backup_dir = os.path.join("data", "backup")
for src in sorted(glob.glob(os.path.join("data", "reports", "*.csv"))):
filename = os.path.basename(src)
dest = os.path.join(backup_dir, filename + ".bak")
print(src, "->", dest)The pathlib version:
from pathlib import Path
backup_dir = Path("data") / "backup"
for src in sorted((Path("data") / "reports").glob("*.csv")):
dest = backup_dir / (src.name + ".bak")
print(src, "->", dest)The second version has no helper modules beyond pathlib, and it keeps path values as path objects until you print them. Nothing here touches the disk except the glob call. Constructing and combining paths never reads or writes the file system. The chapter on pure and concrete paths explains why that matters.
Limits and trade-offs
pathlib is not a strict improvement in every situation, and you should know where it stops.
- Strings still appear at the edges. Many libraries, older code, and command-line arguments use
str. Since Python 3.6,Pathimplementsos.PathLike, so the standard library, includingopen,os.listdir, andshutil, accepts it directly. Some third-party code still needsstr(path). A later chapter covers this. - Overhead. Creating
Pathobjects costs more than handling plain strings. For a hot loop over millions of names, the difference can be measurable. For ordinary scripts it is not. - Not a security boundary. Joining and normalizing paths does not make an untrusted path safe. A segment such as
"/etc"or".."can lead outside the folder you intended. Later chapters show how to check for this. - Version differences. Some features arrive in later versions. For example,
Path.walkwas added in Python 3.12 andPath.is_relative_toin Python 3.9. Check the documentation when you support older interpreters.
Converting at function boundaries
The tip above looks like this in code. The function accepts either type and returns a Path.
from pathlib import Path
def backup_name(source: str | Path) -> Path:
"""Return the backup path for a source file."""
source = Path(source)
return source.with_name(source.name + ".bak")
print(backup_name("notes/draft.txt")) # notes/draft.txt.bak
print(backup_name(Path("notes/draft.txt"))) # notes/draft.txt.bakCalling Path(source) on something that is already a Path returns an equal object, so the conversion is safe to repeat.
What the rest of the tutorial covers
The remaining chapters build on the model in this chapter. You will learn the split between pure and concrete paths, joining and taking apart paths, deriving new paths, resolving relative paths, querying and changing the file system, searching with glob and rglob, working with APIs that expect strings, handling Windows paths on any system, and the pitfalls that cause real bugs.
Exercise
The string "data//logs/./app.log" is passed to Path(...). What does print show on a POSIX system, and why does Path("data/../logs") still show the .. segment?
Show answer
The first prints data/logs/app.log, because Path collapses repeated separators and drops . segments when it builds the object. The second keeps .. because removing it could point to a different file when a directory in the path is a symbolic link. Only the file system can say what .. means, so Path leaves it alone.
Exercise
Rewrite this string code with pathlib so it returns a Path and works for both str and Path input: os.path.splitext(os.path.basename(p))[0] + ".json" joined to the folder "out".
Show answer
from pathlib import Path
def json_target(p):
return Path("out") / (Path(p).stem + ".json")
Path(p).stem replaces the basename plus splitext pair. The / operator replaces os.path.join. For "data/a.csv" the result is out/a.json.