Verify a ZIP archive with testzip

ZipFile.testzip() provides a whole-archive integrity check based on ZIP member headers and CRC values. The example creates a temporary archive with first.txt and second.txt, reopens it, and calls testzip(). For this known-good archive, the method returns None; the assertion records that expected result and the program prints CRC check: passed.

Unlike a quick magic-number check, testzip() reads every member to verify its stored CRC and headers. That makes it appropriate when an application wants to detect ordinary ZIP corruption before consuming all member contents. If it finds a problem, it returns the name of the first bad member instead of raising a success value. The printed conditional makes that distinction clear without relying on an implementation-specific exception.

This example requires Python 3.6.2+ because it supplies a pathlib.Path to ZipFile; testzip() is not a newer API. A passing result only says that this check did not find a bad header or CRC in the archive. It does not authenticate the archive’s origin, establish that contents are safe or expected, enforce extraction path rules, or detect every malicious or application-level problem. Since all fixture data is generated locally in a temporary directory, the assertion checks one predictable successful case rather than proving broader reliability.

See the official ZipFile.testzip documentation and the ZipFile reference.

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) / "checked.zip"

    with ZipFile(archive_path, "w") as archive:
        archive.writestr("first.txt", "one\n")
        archive.writestr("second.txt", "two\n")

    with ZipFile(archive_path) as archive:
        first_bad_name = archive.testzip()

    assert first_bad_name is None
    print("CRC check:", "passed" if first_bad_name is None else first_bad_name)
CRC check: passed

Comments

Popular posts from this blog

Compare Two Text Files in Python Without Modifying Them

Seven CSV Quality Checks to Run Before Importing Data

Explain why SQLite transactions cannot make an HTTP call atomic