List ZIP member names without extracting
Also published in our Blogger archive.
A ZIP archive can be inspected without placing any of its members on the filesystem. Here, a temporary archive is populated with two entries: docs/guide.txt and src/main.py. After reopening it in the default read mode, namelist() returns archive member names in archive order. The program asserts that order and then prints each name.
No call to extract() or extractall() occurs. The example therefore demonstrates listing metadata, not recovering either member’s contents. namelist() returns names rather than ZipInfo records; use infolist() when attributes such as uncompressed size or CRC are needed. A name is archive metadata, not proof that it is suitable to extract or that its contents are trustworthy. In particular, inspect and validate names before designing an extraction workflow for an archive from an untrusted source.
This code requires Python 3.6.2+ because ZipFile receives a pathlib.Path. ZipFile.namelist() itself is an established API rather than a newer-version feature. Output remains deterministic because the example writes entries in a specified sequence. The assertion checks this exact fixture; it does not promise that every producer orders members in the same way, and duplicate member names can exist in ZIP files.
Consult the official ZipFile.namelist and ZipFile.infolist 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 ZipFile
with TemporaryDirectory() as directory:
archive_path = Path(directory) / "bundle.zip"
with ZipFile(archive_path, "w") as archive:
archive.writestr("docs/guide.txt", "Read me.\n")
archive.writestr("src/main.py", "print('ok')\n")
with ZipFile(archive_path) as archive:
names = archive.namelist()
assert names == ["docs/guide.txt", "src/main.py"]
for name in names:
print(name)
docs/guide.txt
src/main.py