Create named, timestamped backups rather than silently overwriting one file.
How It Works
Versioned archives make it easier to recover a prior state. Give each backup a collision-resistant timestamp or identifier, place it in a separate backup directory and verify its contents. The demo creates two archives in a disposable folder and reads the names back.
A production retention policy should consider space limits, off-site copies and verified restore procedures.
Step-by-Step Example
from pathlib import Path
from tempfile import TemporaryDirectory
import zipfile
with TemporaryDirectory() as folder:
root = Path(folder)
source = root / "settings.txt"
source.write_text("mode=safe", encoding="utf-8")
for version in (1, 2):
target = root / f"backup-{version:03}.zip"
with zipfile.ZipFile(target, "x") as archive:
archive.write(source, arcname="settings.txt")
print(sorted(path.name for path in root.glob("backup-*.zip")))
Understanding the Example
- The with block manages the opened resource and closes it when the block finishes, including when an exception occurs.
- The expression 'Path(folder)' supplies the value stored as 'root'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
['backup-001.zip', 'backup-002.zip']
Where This Fits in a Real Program
A practical archive workflow has separate decisions for selection, compression, extraction and verification. When files come from other people, inspect paths, member counts and uncompressed sizes before writing anything; a successful decompression does not establish that its contents are trustworthy.
Practice: Try It Yourself
Extend the loop to generate a third backup and read an entry from each archive.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Overwriting the last good backup instead of keeping more than one recoverable version.
- Creating archives without validating that the expected files were included.
Key Takeaways
- Create named, timestamped backups rather than silently overwriting one file.
- Versioned archives make it easier to recover a prior state.
- A production retention policy should consider space limits, off-site copies and verified restore procedures.