pathlib.Path
An object-oriented representation of a filesystem path, and the standard, cross-platform way to build and manipulate paths.
Path(*segments)
Purpose
Path represents a filesystem path as an object with methods, replacing manual string
concatenation (directory + "/" + filename) with something that works correctly on both
Windows (\) and POSIX (/) path separators.
Example
from pathlib import Path
directory = Path("data")
config_path = directory / "config.json" # Path('data/config.json')
config_path.write_text('{"ready": true}', encoding="utf-8")
text = config_path.read_text(encoding="utf-8")
print(config_path.name) # "config.json"
print(config_path.suffix) # ".json"
print(config_path.parent) # Path('data')
Behavior notes
- The
/operator joins path segments (directory / "config.json") β this isPathβs own operator overload, not filesystem division, and it produces the correct separator for whichever platform the code runs on. read_text()/write_text()(and their binary counterpartsread_bytes()/write_bytes()) open the file, do the operation, and close it again, all in one call β no explicitwithblock needed for this common case, though a context manager is still what happens internally.Pathobjects are immutable β/and methods like.with_suffix(...)return a newPathrather than modifying the original, the same immutability shapestrhas.- Always pass
encoding="utf-8"explicitly for text methods rather than relying on the platform default encoding, which differs between operating systems and can silently produce different bytes for the same text.
Common mistakes
- Building paths with string concatenation or manual
/characters ("data/" + filename) instead ofPathβ this breaks on Windows, where the native separator is\, and doesnβt normalize redundant separators or..segments the wayPathdoes. - Omitting
encoding="utf-8"and relying on the platform default β code that βworksβ during development can produce garbled output (or crash on genuinely non-ASCII text) once it runs somewhere with a different default encoding.
Implementation notes
Pathβs cross-platform behavior β producing the correct separator and semantics for the running
operating system β is a documented, language-guaranteed feature of the standard library, not a
CPython-specific detail.