FIND YOUR NEXT FEW LINES

The snippet library.

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

125 snippets foundClear filters
PythonGetting Started

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
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
PythonMappings & sets

Copy nested mutable data independently

Python: Use deepcopy when changes to nested lists must not affect the original object.

Python✓ Tested
PythonDates & time zones

Count days between calendar dates

Python: Subtract date objects to get an exact calendar-day difference.

Python✓ Tested
PythonCollections

Count occurrences in a list

Count how often each value appears using Counter from the standard library.

count✓ Tested
PythonGetting Started

Count the items in a collection

Python: Read the collection’s length instead of hard-coding the loop limit.

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
PythonFiles & paths

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
PythonDates & time zones

Determine whether a year is a leap year

Python: Use calendar.isleap rather than a simplified divisibility-by-four check.

Python✓ Tested
PythonGetting Started

Divide using a fractional number

Python: Use a floating-point operand to preserve the fractional part of a division.

Python✓ Tested
PythonText validation & encoding

Encode and decode binary data as Base64

Python: Use Base64 when a text format must carry bytes; it is encoding, not encryption.

Python✓ Tested