A compressed backup script should select files deliberately, store relative archive names, and verify that the output can be read.
How It Works
A compressed backup script should select files deliberately, store relative archive names, and verify that the output can be read. A backup is useful only when restoration has been tested; keep independent copies and avoid including secrets unintentionally.
Step-by-Step Example
import tempfile
import zipfile
from pathlib import Path
with tempfile.TemporaryDirectory() as temporary_directory:
working_path = Path(temporary_directory)
source_path = working_path / 'inventory.csv'
source_path.write_text('item,count\npens,8\n', encoding='utf-8')
backup_path = working_path / 'inventory-backup.zip'
with zipfile.ZipFile(backup_path, 'w', compression=zipfile.ZIP_DEFLATED) as archive:
archive.write(source_path, arcname='inventory.csv')
with zipfile.ZipFile(backup_path) as archive:
print(archive.testzip() is None)
print(archive.read('inventory.csv').decode('utf-8'))
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(temporary_directory)' supplies the value stored as 'working_path'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
True
item,count
pens,8
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
Create a zipped backup of a temporary report and verify its contents after saving.
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
- Assuming a successfully written archive is automatically a valid, secure or independently restorable backup.
- Keep restored data outside the source folder when testing a real backup.
Key Takeaways
- A compressed backup script should select files deliberately, store relative archive names, and verify that the output can be read.
- A compressed backup script should select files deliberately, store relative archive names, and verify that the output can be read.
- Keep restored data outside the source folder when testing a real backup.