pythonbeginner
Python Pathlib File Operations
Modern file system operations using pathlib for cross-platform path handling and file management.
pythonPress ⌘/Ctrl + Shift + C to copy
from pathlib import Path
# Path creation and navigation
cwd = Path.cwd()
home = Path.home()
config = home / ".config" / "myapp" / "settings.json"
# Path info
print(config.name) # settings.json
print(config.stem) # settings
print(config.suffix) # .json
print(config.parent) # ~/.config/myapp
print(config.parts) # ('/', 'Users', ...)
# Create directories
output = Path("output/reports/2024")
output.mkdir(parents=True, exist_ok=True)
# Read and write files
path = Path("data.txt")
path.write_text("Hello, World!")
content = path.read_text()
# Binary files
binary_path = Path("image.bin")
binary_path.write_bytes(b"\x89PNG...")
data = binary_path.read_bytes()
# Glob patterns
for py_file in Path("src").rglob("*.py"):
print(py_file)
# List directory contents
for item in Path(".").iterdir():
kind = "DIR" if item.is_dir() else "FILE"
print(f"[{kind}] {item.name}")
# Path checks
path = Path("somefile.txt")
path.exists() # True/False
path.is_file() # True/False
path.is_dir() # True/False
# Rename / move
old = Path("old_name.txt")
old.rename("new_name.txt")
# Get file info
stats = Path("data.csv").stat()
print(f"Size: {stats.st_size} bytes")
print(f"Modified: {stats.st_mtime}")
# Resolve relative paths
absolute = Path("../project/src").resolve()
relative = Path("/a/b/c").relative_to("/a")Use Cases
- Cross-platform file path handling
- Directory traversal and file discovery
- Reading and writing files with clean API
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonbeginner
Pathlib File Operations
Modern file system operations using pathlib for reading, writing, globbing, and path manipulation.
Best for: File processing scripts
#pathlib#filesystem
pythonadvanced
Pathlib Path
Advanced Python pattern: pathlib-path
Best for: advanced programming
#python#advanced
pythonbeginner
Dataclass with Validation
Python dataclass with __post_init__ field validation, type coercion, and descriptive error messages.
Best for: Data transfer objects
#dataclass#validation
pythonintermediate
Custom Context Manager
Context managers for resource management using both class-based and decorator approaches with error handling.
Best for: Database connection management
#context-manager#resource-management