Inspect ZIP Members before Reading
Core idea
A ZIP archive stores named members and metadata. ZipFile.infolist returns ZipInfo objects; filename, file_size and compress_size describe the member. Use a ZipInfo object to identify a specific entry even if names repeat. Inspect names, types and size limits before reading or extracting.
from zipfile import ZipFilefrom io import BytesIOb = BytesIO()with ZipFile(b, "w") as z: z.writestr("report.txt", b"abc")with ZipFile(b) as z: for member in z.infolist(): print(member.filename, member.file_size)Metadata can be inspected without extracting the member to disk.
Read an explicitly selected member
from zipfile import ZipFilefrom io import BytesIOb = BytesIO()with ZipFile(b, "w") as z: z.writestr("data.txt", "ok")with ZipFile(b) as z: info = z.getinfo("data.txt") with z.open(info) as f: print(f.read(2))The selected member is read as bytes without creating a filesystem path.
Common mistake
Metadata is not proof of safety. Reject unexpected paths, duplicates and types; enforce actual decompressed-byte limits and avoid extracting unknown archives blindly.
Practice
Create an in-memory archive with two known names; print each name and declared size, then read only the selected entry.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
ZIP metadata
Check your understanding of zip member inspection.
What is printed?
from zipfile import ZipFilefrom io import BytesIOb=BytesIO()with ZipFile(b,"w") as z: z.writestr("x",b"1234")with ZipFile(b) as z: print(z.getinfo("x").file_size)What is printed?
from zipfile import ZipFilefrom io import BytesIOb=BytesIO()with ZipFile(b,"w") as z: z.writestr("a",b"x")with ZipFile(b) as z: print(z.namelist())Which object can identify one member if names repeat?
What should be done before extracting an unknown archive?