Pathlib File Operations
Modern file system operations using pathlib for reading, writing, globbing, and path manipulation.
from pathlib import Path
# Path construction
base = Path.home() / "projects" / "myapp"
config = base / "config" / "settings.json"
# Read / write
config.parent.mkdir(parents=True, exist_ok=True)
config.write_text('{"debug": true}')
data = config.read_text()
# Glob patterns
py_files = list(base.rglob("*.py"))
test_files = list(base.glob("tests/test_*.py"))
# Path info
print(config.stem) # 'settings'
print(config.suffix) # '.json'
print(config.exists()) # True
print(config.is_file()) # True
# Rename / move
new_path = config.with_suffix(".yaml")
config.rename(new_path)
# Iterate directory
for item in base.iterdir():
kind = "dir" if item.is_dir() else "file"
print(f"{kind}: {item.name}")Use Cases
- File processing scripts
- Config file management
- Directory traversal
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
File Upload with Multer
Configure Multer for disk storage with file type validation, size limits, and unique filenames for Express.
Stream File Download
Express handler that streams a file to the client with proper headers, range support, and error handling.
Async HTTP Client with httpx
Production-ready async HTTP client using httpx with retries, timeouts, and connection pooling.
Retry Decorator with Exponential Backoff
Generic retry decorator with configurable attempts, exponential backoff, and exception filtering.