Python pathlib: The Modern Way to Handle File Paths

python dev.to

Python pathlib: The Modern Way to Handle File Paths

pathlib makes file system operations intuitive and cross-platform. Stop using os.path.

The Basics

from pathlib import Path

# Current directory
cwd = Path.cwd()
print(cwd)  # /home/user/projects

# Home directory
home = Path.home()
print(home)  # /home/user

# Build paths with /
config = home / ".config" / "myapp" / "settings.json"
print(config)  # /home/user/.config/myapp/settings.json
Enter fullscreen mode Exit fullscreen mode

Creating and Checking Paths

from pathlib import Path

p = Path("/tmp/myapp")

# Create directories
p.mkdir(parents=True, exist_ok=True)

# Check existence
print(p.exists())    # True
print(p.is_dir())    # True
print(p.is_file())   # False

# File operations
file = p / "data.txt"
file.write_text("Hello, pathlib!")
print(file.read_text())  # Hello, pathlib!

# File info
print(file.stat().st_size)  # file size in bytes
print(file.suffix)   # .txt
print(file.stem)     # data
print(file.name)     # data.txt
print(file.parent)   # /tmp/myapp
Enter fullscreen mode Exit fullscreen mode

Finding Files (glob)

from pathlib import Path

project = Path(".")

# Find all Python files
for py_file in project.rglob("*.py"):
    print(py_file)

# Find files in current dir only
for f in project.glob("*.json"):
    print(f)

# Find all log files older than 7 days
import time
week_ago = time.time() - 7 * 86400
old_logs = [
    f for f in project.rglob("*.log")
    if f.stat().st_mtime < week_ago
]
Enter fullscreen mode Exit fullscreen mode

Reading and Writing

from pathlib import Path
import json

config_file = Path("config.json")

# Write
config = {"host": "localhost", "port": 8080}
config_file.write_text(json.dumps(config, indent=2))

# Read
data = json.loads(config_file.read_text())

# Read lines
for line in Path("data.csv").read_text().splitlines():
    process(line)

# Write bytes
Path("image.png").write_bytes(image_data)
Enter fullscreen mode Exit fullscreen mode

Practical Utilities

from pathlib import Path
import shutil

# Safe delete
def safe_delete(path: Path) -> bool:
    try:
        if path.is_file():
            path.unlink()
        elif path.is_dir():
            shutil.rmtree(path)
        return True
    except Exception:
        return False

# Ensure directory exists
def ensure_dir(path: Path) -> Path:
    path.mkdir(parents=True, exist_ok=True)
    return path

# Get unique filename
def unique_path(directory: Path, name: str) -> Path:
    path = directory / name
    stem, suffix = path.stem, path.suffix
    counter = 1
    while path.exists():
        path = directory / f"{stem}_{counter}{suffix}"
        counter += 1
    return path
Enter fullscreen mode Exit fullscreen mode

Follow me for more Python tips! 🐍


💡 Related: **Content Creator Ultimate Bundle (Save 33%)* — $29.99*

Source: dev.to

arrow_back Back to Tutorials