zipfile-zstd

0.0.4 · maintenance · verified Thu Apr 16

zipfile-zstd is a Python library that monkey patches the standard `zipfile` module to enable support for Zstandard compression. It allows both compressing and decompressing files within ZIP archives using the highly efficient Zstandard algorithm. The library is currently at version 0.0.4, with its last release in December 2021, and its primary purpose is to add Zstandard capabilities to Python versions older than 3.14. It relies on the `python-zstandard` library for the underlying Zstandard bindings.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a ZIP archive using Zstandard compression and then extract its contents. It first enables the `zipfile-zstd` monkey-patch, then uses the standard `zipfile.ZipFile` class with the `ZIP_ZSTANDARD` constant for compression. It concludes with cleanup of the created files.

import zipfile_zstd
import os
from pathlib import Path

# Enable Zstandard support for the standard zipfile module
zipfile_zstd.enable_zstandard()

# ZIP_ZSTANDARD constant is now available in the patched zipfile module
# or can be imported directly from zipfile_zstd
from zipfile_zstd import ZIP_ZSTANDARD
import zipfile # The standard zipfile module is now patched

archive_name = "example_zstd.zip"
file_to_compress = "test_file.txt"
extracted_dir = "extracted_zstd"

# Create a dummy file for compression
Path(file_to_compress).write_text("This is a test file to be compressed with Zstandard.\n")

try:
    # 1. Create a Zstandard compressed ZIP archive
    print(f"Creating {archive_name} with Zstandard compression...")
    with zipfile.ZipFile(archive_name, 'w', compression=ZIP_ZSTANDARD) as zf:
        zf.write(file_to_compress)
    print(f"Successfully created {archive_name}.")

    # 2. Read and extract from the Zstandard compressed ZIP archive
    print(f"Extracting from {archive_name}...")
    os.makedirs(extracted_dir, exist_ok=True)
    with zipfile.ZipFile(archive_name, 'r') as zf:
        zf.extractall(extracted_dir)
    print(f"Content extracted to {extracted_dir}.")

    # Verify content
    extracted_file_path = Path(extracted_dir) / file_to_compress
    if extracted_file_path.exists():
        print(f"Extracted content: {extracted_file_path.read_text().strip()}")
    else:
        print("Extraction failed or file not found.")

finally:
    # Clean up created files and directories
    if Path(file_to_compress).exists():
        os.remove(file_to_compress)
    if Path(archive_name).exists():
        os.remove(archive_name)
    if Path(extracted_dir).exists():
        import shutil
        shutil.rmtree(extracted_dir)
    print("Cleanup complete.")

view raw JSON →