FIND YOUR NEXT FEW LINES

The snippet library.

Small, practical examples. Search by task or narrow things down below.

10 snippets foundClear filters
PythonFile operations & archives

Clean up a temporary directory automatically

Python: Use TemporaryDirectory as a context manager so cleanup also happens after exceptions.

Python✓ Tested
PythonFile operations & archives

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
PythonFile operations & archives

Create a file without overwriting an existing one

Python: Use exclusive creation mode and handle FileExistsError explicitly.

Python✓ Tested
PythonFile operations & archives

Create a ZIP archive from a file

Python: Give a ZIP entry a relative archive name instead of exposing its source directory.

Python✓ Tested
PythonFile operations & archives

Extract filename components

Python: Use pathlib properties to separate a directory, filename stem, and suffix.

Python✓ Tested
PythonFile operations & archives

Find matching files recursively

Python: Use rglob and sorted relative paths for a reproducible recursive file listing.

Python✓ Tested
PythonFile operations & archives

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
PythonFile operations & archives

Read a file size in bytes

Python: Use stat().st_size to read the logical byte length without loading the file.

Python✓ Tested
PythonFile operations & archives

Read compressed text directly

Python: Open gzip data in text mode with an explicit encoding.

Python✓ Tested
PythonFile operations & archives

Rename a file within a directory

Python: Use Path.rename and inspect the resulting path.

Python✓ Tested