FIND YOUR NEXT FEW LINES

Results for “Python”

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

125 snippets foundClear filters
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
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
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
PythonText validation & encoding

Escape text for HTML content

Python: Use html.escape before placing plain text in an HTML text or quoted attribute context.

Python✓ Tested
PythonGetting Started

Explain a calculation with a comment

Python: Keep the code executable while documenting why a fixed input is used.

Python✓ Tested
PythonFile operations & archives

Extract filename components

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

Python✓ Tested