Read one ZIP member as text
To read one chosen member without extracting it, open the archive and then call ZipFile.open() with its member name. This example creates messages.zip in a temporary directory with two text members, but selects only message.txt. In read mode, open() returns a binary file-like object. The program calls read() and decodes the returned bytes explicitly as UTF-8, producing Hello, ZIP! followed by its newline.
The assertion checks that the full decoded string is exactly Hello, ZIP!\n. print(text, end="") preserves the member’s terminal newline and avoids adding another one, which makes the stated stdout exact. The second member, other.txt, remains unread and demonstrates that selecting one member does not require extracting or reading all members.
This requires Python 3.6.2+ because ZipFile is given a pathlib.Path; reading with ZipFile.open() is older. The code assumes the selected bytes are UTF-8. A different encoding can raise UnicodeDecodeError or produce incorrect text if decoded with the wrong codec. A missing member causes an error, and duplicate archive names require more deliberate handling: the documentation allows a ZipInfo object where exact member identity matters. Reading text successfully does not validate the archive’s source, all of its contents, or its suitability for an extraction workflow.
See the official ZipFile.open and ZipFile.read 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) / "messages.zip"
with ZipFile(archive_path, "w") as archive:
archive.writestr("message.txt", "Hello, ZIP!\n")
archive.writestr("other.txt", "not selected\n")
with ZipFile(archive_path) as archive:
with archive.open("message.txt") as member:
text = member.read().decode("utf-8")
assert text == "Hello, ZIP!\n"
print(text, end="")
Hello, ZIP!
Comments
Post a Comment