Library contents

Python ZipFile.close

Close the ZIP archive after checking one of its members.

A simple example

ZipFile.close

  1. Start with An open archive
  2. Do this Close the archive
  3. Result Archive handle released
Finish reading entries before closing the archive that owns them.

Syntax

Python syntax
archive.close()
Run these examples in Python

Save one example at a time as lesson.py. Use Python 3.9 or later.

python3 lesson.py

Finish reading an archive

An archive reader finishes working with an entry or the surrounding archive. Release the appropriate handle at that boundary so processing later receipts does not accumulate open resources.

Resulttea.txt
lesson.py
from io import BytesIO
from zipfile import ZipFile, ZIP_STORED

store = BytesIO()
with ZipFile(store, "w", compression=ZIP_STORED) as archive:
    archive.writestr("tea.txt", "paid")

store.seek(0)
with ZipFile(store) as archive:
    print(archive.getinfo("tea.txt").filename)
    archive.close()
Output
tea.txt

Closing releases resources held by the archive. A with block also closes it if reading fails.

Advertisements

Inspect a choir archive

A teacher saves the bytes for the word alto in an uncompressed archive member. The reader finishes its work and closes the archive handle. What is the state of that resource?

Givenparts/alto.txt · 4 bytes
Worked resultClosed

The archive contains one stored member. Its entry metadata and contents can be inspected independently.

Inspect a workshop archive

A tutor saves the bytes for glaze in a second uncompressed archive member. The reader finishes its work and closes the archive handle. What is the state of that resource?

Givenstudio/tag.txt · 5 bytes
Worked resultClosed

The archive contains one stored member. Its entry metadata and contents can be inspected independently.

What to watch for

For an archive supplied by someone else, check expected member names and size limits before reading large payloads.

Documentation for ZipFile.close