Results for “Python”
Small, practical examples. Search by task or narrow things down below.
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 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
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
Escape text for HTML content
Python: Use html.escape before placing plain text in an HTML text or quoted attribute context.
Python✓ Tested
Explain a calculation with a comment
Python: Keep the code executable while documenting why a fixed input is used.
Python✓ Tested
Extract filename components
Python: Use pathlib properties to separate a directory, filename stem, and suffix.
Python✓ Tested