The snippet library.
Small, practical examples. Search by task or narrow things down below.
Convert known numeric text to an integer
Python: Convert a trusted literal to an integer before adding. Validate external input before converting it.
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
Copy nested mutable data independently
Python: Use deepcopy when changes to nested lists must not affect the original object.
Python✓ Tested
Count days between calendar dates
Python: Subtract date objects to get an exact calendar-day difference.
Python✓ Tested
Count occurrences in a list
Count how often each value appears using Counter from the standard library.
count✓ Tested
Count the items in a collection
Python: Read the collection’s length instead of hard-coding the loop limit.
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
Create nested folders
Create a folder and any missing parent folders in one call. Running the code again is safe when the folder already exists.
directory✓ Tested
Determine whether a year is a leap year
Python: Use calendar.isleap rather than a simplified divisibility-by-four check.
Python✓ Tested
Divide using a fractional number
Python: Use a floating-point operand to preserve the fractional part of a division.
Python✓ Tested
Encode and decode binary data as Base64
Python: Use Base64 when a text format must carry bytes; it is encoding, not encryption.
Python✓ Tested