pythonbeginner
Pathlib File Operations
Modern file system operations using pathlib for reading, writing, globbing, and path manipulation.
pythonPress ⌘/Ctrl + Shift + C to copy
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.
pythonbeginner
Python Pathlib File Operations
Modern file system operations using pathlib for cross-platform path handling and file management.
Best for: Cross-platform file path handling
#python#pathlib
pythonadvanced
Pathlib Path
Advanced Python pattern: pathlib-path
Best for: advanced programming
#python#advanced
typescriptintermediate
File Upload with Multer
Configure Multer for disk storage with file type validation, size limits, and unique filenames for Express.
Best for: Profile avatar uploads
#express#upload
typescriptadvanced
Stream File Download
Express handler that streams a file to the client with proper headers, range support, and error handling.
Best for: Large file downloads
#stream#download