Archive two generated text members with zipfile
Also published in our Blogger archive.
This example creates notes.zip inside TemporaryDirectory, so the archive exists only for the duration of the block. The generated dictionary supplies two pieces of text: build.txt contains status=ready, and metrics.txt contains count=2. ZipFile(..., "w") creates a new archive, while writestr() writes text directly as a member; when its data argument is a string, zipfile encodes it as UTF-8.
The second ZipFile context reopens the archive and uses read() to get each member as bytes before decoding UTF-8. The assertion compares the complete reconstructed mapping with the original input, checking both member selection and exact text in this controlled fixture. The two printed lines are deliberately derived from the known input, making stdout stable even though ZIP metadata such as timestamps may vary.
This requires Python 3.6.2+ because the example passes a pathlib.Path to ZipFile; writestr() and the ZipFile context-manager pattern are older APIs. ZIP_STORED avoids requiring an optional compression module, but it does not compress data. This assertion does not establish that another ZIP tool will support every archive feature, nor does it validate untrusted input. The standard library does not create encrypted ZIP members.
See the official ZipFile and ZipFile.writestr documentation.
AI-assistance disclosure: This article was drafted with AI assistance and should be reviewed for its intended use.
from pathlib import Path
from tempfile import TemporaryDirectory
from zipfile import ZIP_STORED, ZipFile
with TemporaryDirectory() as directory:
archive_path = Path(directory) / "notes.zip"
generated = {
"build.txt": "status=ready\n",
"metrics.txt": "count=2\n",
}
with ZipFile(archive_path, "w", compression=ZIP_STORED) as archive:
for name, text in generated.items():
archive.writestr(name, text)
with ZipFile(archive_path) as archive:
restored = {
name: archive.read(name).decode("utf-8")
for name in generated
}
assert restored == generated
print("build.txt: status=ready")
print("metrics.txt: count=2")
build.txt: status=ready
metrics.txt: count=2