`pathlib` — Object-Oriented File Paths
Python · Standard Library · Run with python3
Explanation
`pathlib.Path` (Python 3.4+) replaces string-based path manipulation with an object-oriented API. Paths are composed with `/`: `base / "subdir" / "file.txt"`. Key methods: `Path.read_text()`, `Path.write_text()`, `Path.glob("**/*.py")`, `Path.rglob()`, `Path.exists()`, `Path.mkdir(parents=True, exist_ok=True)`, `Path.stat()`. `Path.home()` and `Path.cwd()` give the home/current directory.
Real-World Scenario
Finding all Python files in a project and reporting their line counts: `list(Path(".").rglob("*.py"))` — one line replaces `os.walk` + filtering. Reading a config file from the same directory as the script: `Path(__file__).parent / "config.json"`. ```python from pathlib import Path # Build paths with / operator project_root = Path(__file__).parent.parent config_path = project_root / "config" / "settings.json" # Glob for all Python source files py_files = sorted(project_root.rglob("*.py")) print(f"Found {len(py_files)} Python files") # Safe read with fallback if config_path.exists(): text = config_path.read_text(encoding="utf-8") print(f"Config size: {len(text)} bytes") # Write atomically by writing to temp then rename output = Path("result.txt") tmp = output.with_suffix(".tmp") tmp.write_text("processed data\n", encoding="utf-8") tmp.rename(output) print(f"Written to {output.resolve()}") ```
Quick Snippet
from pathlib import Path
# Build paths with / operator
project_root = Path(__file__).parent.parent
config_path = project_root / "config" / "settings.json"
# Glob for all Python source files
py_files = sorted(project_root.rglob("*.py"))
print(f"Found {len(py_files)} Python files")
# Safe read with fallback
if config_path.exists():
text = config_path.read_text(encoding="utf-8")
print(f"Config size: {len(text)} bytes")
# Write atomically by writing to temp then rename
output = Path("result.txt")
tmp = output.with_suffix(".tmp")
tmp.write_text("processed data\n", encoding="utf-8")
tmp.rename(output)
print(f"Written to {output.resolve()}")Full Example
# Compile: python3 pathlib_basics.py
# Output:
# Written to result.txt
from pathlib import Path
import tempfile
# Build paths with / operator
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
output = base / "result.txt"
tmp_f = output.with_suffix(".tmp")
# Write atomically
tmp_f.write_text("processed data\n", encoding="utf-8")
tmp_f.rename(output)
print(f"Written to {output.name}")
# Read back
content = output.read_text(encoding="utf-8")
print(f"Content: {content.strip()!r}")
# Glob
(base / "a.py").write_text("# a")
(base / "b.py").write_text("# b")
py_files = sorted(base.glob("*.py"))
print(f"Python files: {[f.name for f in py_files]}")
# Path components
p = Path("/home/user/projects/app/main.py")
print(f"stem: {p.stem}") # main
print(f"suffix: {p.suffix}") # .py
print(f"parent: {p.parent}") # /home/user/projects/app
print(f"parts: {p.parts[:3]}")
python3 pathlib_basics.py