The snippet library.
Small, practical examples. Search by task or narrow things down below.
Clean up a temporary directory automatically
Python: Use TemporaryDirectory as a context manager so cleanup also happens after exceptions.
Python✓ Tested
Copy a file and preserve its metadata
Python: Use copy2 for a file copy that also attempts to preserve timestamps and permission bits.
Python✓ Tested
Create a file without overwriting an existing one
Python: Use exclusive creation mode and handle FileExistsError explicitly.
Python✓ Tested
Create a ZIP archive from a file
Python: Give a ZIP entry a relative archive name instead of exposing its source directory.
Python✓ Tested
Extract filename components
Python: Use pathlib properties to separate a directory, filename stem, and suffix.
Python✓ Tested
Find matching files recursively
Python: Use rglob and sorted relative paths for a reproducible recursive file listing.
Python✓ Tested
Hash a file without reading it all at once
Python: Feed fixed-size binary chunks into SHA-256 for files larger than memory.
Python✓ Tested
Read a file size in bytes
Python: Use stat().st_size to read the logical byte length without loading the file.
Python✓ Tested
Read compressed text directly
Python: Open gzip data in text mode with an explicit encoding.
Python✓ Tested
Rename a file within a directory
Python: Use Path.rename and inspect the resulting path.
Python✓ Tested