Python

pathlib Quick Reference

admin by @admin ADMIN
4m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Forget os.path.* — pathlib.Path is the modern, OS-aware way to work with paths. Operator overloading for joins, attribute access for components, methods for reads/writes/iterations.
Python
Raw
from pathlib import Path

p = Path("/var/log/myapp") / "app.log"     # path join with /
print(p.parent)         # /var/log/myapp
print(p.name)           # app.log
print(p.stem)           # app
print(p.suffix)         # .log

# Exists / type checks
print(p.exists(), p.is_file(), p.is_dir())

# Read / write whole file
text = p.read_text(encoding="utf-8")
p.write_text("hello\n", encoding="utf-8")

# Iterate a directory (lazy)
for child in Path("src").iterdir():
    print(child)

# Glob — recursive **
for py in Path("src").rglob("*.py"):
    print(py)

# Build platform-aware home/config paths
config = Path.home() / ".config" / "myapp.toml"
config.parent.mkdir(parents=True, exist_ok=True)
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.