Definition
The modern object-oriented standard for representing and manipulating file system paths, introduced in Python 3.4.
Why It Matters
File paths are the most common source of “it worked on my machine” bugs. The older way of using strings for paths is fundamentally flawed because paths are not just text—they are hierarchical objects with platform-specific rules. Pathlib is the “abstraction layer” that prevents these bugs. Failing to use it leads to code riddled with if os.name == 'nt' checks and manual string splicing, which is the hallmark of insecure, unmaintainable, and non-portable software.
Core Concepts
- Path Objects: Instead of strings, paths are rich objects. Use
from pathlib import Path. - Operator Overloading (
/): Join paths using the division operator (e.g.,Path('folder') / 'file.txt'). One of the first two operands must be aPathobject. - Location Tools:
Path.cwd(): Current Working Directory.Path.home(): User’s home directory.
- Path Components:
p.name(filename),p.stem(no extension),p.suffix(extension),p.parent(directory). - Validation:
p.exists(),p.is_file(),p.is_dir(). - Shortcuts:
p.read_text()andp.write_text()handle the open/read/close lifecycle in a single call for simple text files.
from pathlib import Path
# Creating a path object
path = Path('documents') / 'notes.txt'
# Checking attributes
print(f"File: {path.name}")
print(f"Directory: {path.parent}")
if path.exists():
content = path.read_text()