zipfile Round Trips An Archive In Memory

Create, read, and verify a ZIP archive entirely in memory with zipfile and BytesIO, including member metadata and a corruption check.

PythonData Integrity

Code

pythonsnippet
31 lines
import io
import zipfile


def main() -> None:
    files = {'notes.txt': 'first entry\n', 'data/config.json': '{"ok": true}\n'}
    buffer = io.BytesIO()

    # 写入:ZIP_DEFLATED 压缩,writestr 接受字符串或字节
    with zipfile.ZipFile(buffer, 'w', zipfile.ZIP_DEFLATED) as archive:
        for name, text in files.items():
            archive.writestr(name, text)

    print('archive bytes:', len(buffer.getvalue()))

    # 读取:namelist 与 read 都不需要落盘
    buffer.seek(0)
    with zipfile.ZipFile(buffer, 'r') as archive:
        print('members:', archive.namelist())
        info = archive.getinfo('notes.txt')
        print('size/compressed:', info.file_size, info.compress_size)
        print('content:', archive.read('notes.txt').decode('utf-8').strip())

    # 完整性校验:testzip 返回第一个坏成员名或 None
    buffer.seek(0)
    with zipfile.ZipFile(buffer, 'r') as archive:
        print('corrupt member:', archive.testzip())


if __name__ == '__main__':
    main()

What the code does

Count the function main as the entire surface area of zipfile Round Trips An Archive In Memory.

Iteration happens inside for name, text in files.items() — everything outside it runs once.

What to watch for

  • Dependency check: zipfile — not built-in, must be present in the project.

Using it

Look for the archive bytes:, members:, size/compressed: prefixes when the file runs; they tie each line to its step.

Key statements

with zipfile.ZipFile(buffer, 'w', zipfile.ZIP_DEFLATED) as archive:
    for name, text in files.items():
        archive.writestr(name, text)
with zipfile.ZipFile(buffer, 'r') as archive:
    print('members:', archive.namelist())
    info = archive.getinfo('notes.txt')
    print('size/compressed:', info.file_size, info.compress_size)
    print('content:', archive.read('notes.txt').decode('utf-8').strip())
with zipfile.ZipFile(buffer, 'r') as archive:
    print('corrupt member:', archive.testzip())

Interactive Tools for This Topic

FAQ

What does zipfile Round Trips An Archive In Memory print when run?
Execute the whole file; each printed line is prefixed with a label like `archive bytes:`, `members:`, `size/compressed:`.