pyzstd: Zstandard Compression
pyzstd provides high-performance Python bindings for the Zstandard (zstd) lossless compression algorithm. It enables fast compression and decompression for bytes-like objects and file streams, leveraging the C zstd library. The current stable version is 0.19.1, and it is actively maintained with regular releases.
Warnings
- breaking In version 0.17.0, the `zstd.compress_file` and `zstd.decompress_file` functions were removed, and the signature of `zstd.open` was changed significantly. Direct file handling methods are no longer available at the top level.
- gotcha The top-level `zstd.compress()` and `zstd.decompress()` functions are designed for bytes-like objects in memory. Attempting to pass file objects directly to them will result in errors or unexpected behavior.
- gotcha Compression levels in `pyzstd` range from 1 to 22 (inclusive), with 3 being the default. Higher levels offer better compression but require significantly more CPU time. Using a value outside this range will raise an error.
Install
-
pip install pyzstd
Imports
- zstd
import zstd
- ZstdCompressor
from zstd import ZstdCompressor
- ZstdDecompressor
from zstd import ZstdDecompressor
Quickstart
import zstd
original_data = b"This is some sample data that will be compressed using Zstandard!"
# Compress data with default level (3)
compressed_data = zstd.compress(original_data)
print(f"Original size: {len(original_data)} bytes")
print(f"Compressed size: {len(compressed_data)} bytes")
# Decompress data
decompressed_data = zstd.decompress(compressed_data)
# Verify data integrity
assert original_data == decompressed_data
print("Data decompressed successfully and matches original.")
# Example with a specific compression level
compressed_level_20 = zstd.compress(original_data, 20)
print(f"Compressed size (level 20): {len(compressed_level_20)} bytes")