Topic 20 of 64
Pathlib & File
Overview
pathlib (Python 3.4+) provides an object-oriented interface for file system paths that works across Windows, macOS, and Linux. It replaces os.path with more readable, chainable operations.
Syntax
python
from pathlib import Path
# Creating paths
home = Path.home() # /Users/username
cwd = Path.cwd() # current directory
p = Path("data/config.json")
abs_p = p.resolve() # absolute path
# Path operations
p.parent # Path("data")
p.name # "config.json"
p.stem # "config"
p.suffix # ".json"
p.parts # ("data", "config.json")
# Joining paths (/ operator!)
data_dir = Path("data")
report_path = data_dir / "2025" / "report.csv"
# Checking
p.exists()
p.is_file()
p.is_dir()
# Reading/Writing
text = p.read_text(encoding="utf-8")
p.write_text("Hello!", encoding="utf-8")
bytes_ = p.read_bytes()
# Listing
for f in Path("data").iterdir():
print(f.name)
# Glob patterns
for csv_file in Path(".").glob("**/*.csv"):
process(csv_file)Common Pitfalls
- Path objects are immutable — operations like / and with_suffix() return NEW Path objects.
- Path.mkdir(parents=True, exist_ok=True) creates all parent directories and doesn't raise if directory exists.
- Interview tip: Use pathlib.Path everywhere instead of os.path — it's more readable, chainable, and works cross-platform.
Real-World Example
A file organizer script using pathlib:
example
python
from pathlib import Path
from shutil import move
from datetime import datetime
def organize_downloads(downloads_dir: Path, output_dir: Path) -> None:
"""Organize files by type and date."""
CATEGORIES = {
"images": {".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg"},
"documents": {".pdf", ".doc", ".docx", ".txt", ".xlsx"},
"code": {".py", ".js", ".ts", ".html", ".css", ".json"},
"archives": {".zip", ".tar", ".gz", ".rar"},
}
for file_path in downloads_dir.iterdir():
if not file_path.is_file():
continue
suffix = file_path.suffix.lower()
date = datetime.fromtimestamp(file_path.stat().st_mtime)
year_month = date.strftime("%Y-%m")
# Find category
category = "other"
for cat, extensions in CATEGORIES.items():
if suffix in extensions:
category = cat
break
# Create destination directory
dest = output_dir / category / year_month
dest.mkdir(parents=True, exist_ok=True)
# Move file
move(str(file_path), str(dest / file_path.name))
print(f"Moved {file_path.name} → {category}/{year_month}/")