ZipFile.
How It Works
ZipFile.write(filename, arcname=...) copies an existing file into a ZIP archive. arcname controls how the file appears inside the ZIP; avoid leaking absolute local filesystem paths as entry names.
Step-by-Step Example
from pathlib import Path
import tempfile
import zipfile
with tempfile.TemporaryDirectory() as temporary_directory:
source_path = Path(temporary_directory) / 'summary.txt'
source_path.write_text('items: 4', encoding='utf-8')
archive_path = Path(temporary_directory) / 'reports.zip'
with zipfile.ZipFile(archive_path, 'w') as archive:
archive.write(source_path, arcname='reports/summary.txt')
with zipfile.ZipFile(archive_path) as archive:
print(archive.namelist())
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) / 'summary.txt'" supplies the value stored as 'source_path'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
['reports/summary.txt']
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
Write a temporary report file into a ZIP under an internal reports/ folder.
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
- Expecting write() to accept raw text instead of a file path or allowing an unwanted folder structure into archives.
- Do not mistake successful decoding or parsing for trust in the contents.
Key Takeaways
- ZipFile.
- ZipFile.write(filename, arcname=...) copies an existing file into a ZIP archive.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.