snippetpythonTippending
Python pathlib complete guide
Viewed 0 times
pathlibpathfilesystemglobread_textwrite_text
Problem
Need to work with file paths in Python using modern, cross-platform pathlib instead of os.path.
Solution
Pathlib recipes for common operations:
from pathlib import Path
# Create paths
p = Path('src') / 'components' / 'Button.tsx' # Joins with /
p = Path.home() / '.config' / 'app' # Home directory
p = Path.cwd() / 'data' # Current directory
# Path information
p.name # 'Button.tsx'
p.stem # 'Button'
p.suffix # '.tsx'
p.suffixes # ['.test', '.tsx'] for 'Button.test.tsx'
p.parent # Path('src/components')
p.parents[1] # Path('src')
p.parts # ('src', 'components', 'Button.tsx')
p.is_absolute() # False
p.resolve() # Absolute path, resolves symlinks
# File operations
p.exists()
p.is_file()
p.is_dir()
p.mkdir(parents=True, exist_ok=True) # Like mkdir -p
# Read/write (no open() needed)
text = p.read_text(encoding='utf-8')
p.write_text('content', encoding='utf-8')
bytes_data = p.read_bytes()
p.write_bytes(b'data')
# Glob patterns
list(Path('src').glob('*.py')) # Direct children
list(Path('src').rglob('*.py')) # Recursive
list(Path('.').glob('**/*.test.tsx')) # Recursive glob
# Rename and move
p.rename('new_name.txt') # Same directory
p.replace(Path('dest') / p.name) # Move (overwrites)
# Temporary files
import tempfile
with tempfile.NamedTemporaryFile(suffix='.json') as f:
tmp = Path(f.name)Why
pathlib provides an object-oriented, cross-platform API for filesystem operations. It's more readable than os.path string manipulation.
Context
Python file and path manipulation
Revisions (0)
No revisions yet.