Batu Lab NotesPractical developer guides

Inspect a ZIP before delivery without extracting it over a workspace

By Batu ยท English technical notes

Also published in our Blogger archive.

Inspect an archive member without extraction

namelist lists recorded members and read returns bytes for a selected member. The example checks both while the ZipFile is open and never calls extract, so no archive member is materialized in a reviewer folder. The byte assertion uses the same name approved by the listing.

read returns the complete decompressed member in memory, so this small-file technique is unsuitable for an unexpectedly large entry. Duplicate names and any later extraction policy need independent handling.

Example

from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as d:
    from zipfile import ZipFile
    z = Path(d) / 'r.zip'
    with ZipFile(z, 'w') as f:
        f.writestr('README.txt', 'synthetic')
    with ZipFile(z) as f:
        assert f.namelist() == ['README.txt']
        assert f.read('README.txt') == b'synthetic'
    result = 'extracted=0'
    print(result)

Expected stdout:

extracted=0

Sources

- zipfile.ZipFile.namelist

- zipfile.ZipFile.read

Prepared with AI assistance. The example uses synthetic data; its stated limits apply.