──────────────────────────────────────

50. Prepare Reports to Share · Pack Two Files into a ZIP

Create a ZIP archive and reopen it to check its filenames and text.

Lesson files · lessons/share-reports/pack-report-files

Before you start
- Use a with block to close a file after writing.
- Read back UTF-8 text and join a list of names for display.

By the end
- Write title.txt and note.txt to a single archive and reopen it.
- Check the member names and confirm that the reopened note preserves accented characters.

Where you can use it
Pack a title and note into one file for a reviewer, and read back the note to check that its accents survived.

A ZIP archive holds several named files together. BytesIO holds the archive in memory and gives ZipFile something to write to. ZipFile in mode "w" creates the archive. Use writestr() with a name and text, which is stored as UTF-8. Leaving the with block finishes the archive. Use buffer.getvalue() to get its bytes. Open the bytes through a new BytesIO object, then use namelist() to see the files or read(name).decode("utf-8") to get their text.

Predict
What does archive.read("sign.txt") give before decode()?
- The filename as a string.
- The file contents as bytes.

Worked example (example.py)

from io import BytesIO
from zipfile import ZipFile

buffer = BytesIO()
with ZipFile(buffer, "w") as archive:
    archive.writestr("sign.txt", "Entry on the left")

with ZipFile(BytesIO(buffer.getvalue())) as archive:
    print(archive.namelist()[0])
    print(archive.read("sign.txt").decode("utf-8"))


Example result
sign.txt
Entry on the left

Read two lines. Store the first in title.txt and the second in note.txt, in that order in one archive. Reopen the archive. Print its filenames with a comma and a space between them. Then print the contents of note.txt on the next line.

Starter program (starter.py)

from io import BytesIO
from zipfile import ZipFile

title = input()
note = input()
buffer = BytesIO()
with ZipFile(buffer, "w") as archive:
    archive.writestr("title.txt", title)

with ZipFile(BytesIO(buffer.getvalue())) as archive:
    print(", ".join(archive.namelist()))


Starter input
Garden Club
Planted beans.

Hint
Write both files before you reopen the ZIP. Use ", ".join(archive.namelist()) to list them.

Case 1. Try the sample
Input
Garden Club
Planted beans.
Expected output
title.txt, note.txt
Planted beans.

Case 2. Preserve accented text
Input
Kitchen Club
Café menu ready.
Expected output
title.txt, note.txt
Café menu ready.

Case 3. Use fixed filenames
Input
Friday Notes
Draft only
Expected output
title.txt, note.txt
Draft only

Stretch
Read title.txt back as well and check whether its contents match the first line of input.

Reflect
Why do you reopen the archive after the writing block has finished?

Check your prediction
The file contents as bytes. read() returns the stored contents. decode() turns those bytes back into text.
