ZipFile.
How It Works
ZipFile.writestr(archive_name, data) writes a string or byte sequence directly to a ZIP entry without first creating a regular file. String input is encoded to UTF-8.
Step-by-Step Example
import io
import zipfile
archive_buffer = io.BytesIO()
with zipfile.ZipFile(archive_buffer, 'w') as archive:
archive.writestr('reports/summary.csv', 'month,total\nOct,42\n')
with zipfile.ZipFile(io.BytesIO(archive_buffer.getvalue())) as archive:
print(archive.read('reports/summary.csv').decode('utf-8'))
Understanding the Example
- The expression 'io.BytesIO()' supplies the value stored as 'archive_buffer'. This value is then used or checked by the later statements.
- The with block manages the opened resource and closes it when the block finishes, including when an exception occurs.
A successful run of this example prints the following output:
month,total
Oct,42
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 ZIP containing a dynamically generated CSV report.
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
- Confusing the entry name with a real destination filesystem path or opening the archive in read mode.
- Do not mistake successful decoding or parsing for trust in the contents.
Key Takeaways
- ZipFile.
- ZipFile.writestr(archive_name, data) writes a string or byte sequence directly to a ZIP entry without first creating a regular file.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.