`pathlib`
pathlib is the standard-library object-oriented API for filesystem paths. A Path joins parts, inspects names, and reads or writes files without string concatenation.
Detailed Explanation
Paths used to be strings. os.path.join(root, "data", filename) works and is easy to get slightly wrong: extra slashes, the wrong separator on Windows, forgetting that join ignores earlier parts after an absolute segment. Path stores the path as an object. / joins: Path("data") / "orders" / "2026.json". The same code uses backslashes on Windows and slashes on Unix.
Path is concrete: Path is PosixPath or WindowsPath on the current machine. PurePath, PurePosixPath, and PureWindowsPath manipulate paths without touching the disk, which is what you want when the path is for another OS.
Common queries: .name is the final component, .stem is the name without the last suffix, .suffix is that suffix, .parent is the directory, .parts is the tuple of components. .with_name and .with_suffix return a new path; Path is immutable in that sense.
I/O methods live on the object. read_text, write_text, read_bytes, write_bytes, open, mkdir, iterdir, glob, rglob, exists, is_file, is_dir, unlink, rename, replace. mkdir(parents=True, exist_ok=True) replaces a nest of os.makedirs flags. path / "child" does not create the child until you write or mkdir.
Path.cwd() and Path.home() are the current directory and the user's home. Path(__file__).resolve().parent is the directory of the current module, which is the reliable way to find data files next to the code. Do not rely on cwd for that; cwd is where the process was started, not where the file lives.
pathlib does not replace every os call. File descriptors, fsync, and some permission bits still go through os. For path manipulation and everyday I/O, prefer Path. Mixing str paths and Path is allowed: most functions accept either, and os.fspath(path) gives the string.
Code Examples
from pathlib import Path
root = Path("data") / "orders"
root.mkdir(parents=True, exist_ok=True)
ticket = root / "ORD-11.json"
ticket.write_text('{"cents": 2500}\n', encoding="utf-8")
print(ticket.read_text(encoding="utf-8"))
print(ticket.name, ticket.suffix, ticket.parent)
# ORD-11.json .json data/ordershere = Path(__file__).resolve().parent
print(here)
print(list(here.glob("*.md"))[:3])# Pure paths do not touch the disk and keep a chosen flavour.
from pathlib import PureWindowsPath
win = PureWindowsPath(r"C:\logs\app.log")
print(win.drive, win.name) # C: app.logCommon Gotchas
`Path("a") / "/etc/passwd"` drops the left side
an absolute right-hand part replaces the path, like `os.path.join`. Join only relative names you control.
`cwd` is not the project root
files next to a module should be resolved from `Path(__file__).parent`, not from `Path("data")`.
`glob` does not expand `~`
use `Path.home()` or `expanduser()`.
`exists()` is a snapshot
a file can disappear between the check and `open`. Catch `FileNotFoundError` instead of pre-testing when you need correctness.