Python Glossary Русский

Python 3.14+compression.zstdterm

compression.zstd.ZstdFile

zstd files

A binary file object that compresses to Zstandard on write and decompresses on read; it also works on top of BytesIO.

Syntax

compression.zstd.ZstdFile(file, /, mode='rb', *, level=None, options=None, zstd_dict=None)

Binary modes only, 'r', 'w', 'x', 'a': 'rt' raises ValueError, so wrap it in io.TextIOWrapper or use zstd.open for text. A file object you pass in is not closed when ZstdFile closes, while a file it opened by name is. Mode 'a' does not extend the old frame but appends a new one; reading returns everything as one stream. level is allowed only for writing; for reading it raises TypeError.

Examples

# Python 3.14+
from compression import zstd  # → ? нужна сборка CPython с libzstd
with zstd.ZstdFile('log.zst', 'w', level=10) as f:
    f.write(b'abc')
with zstd.ZstdFile('log.zst', 'a') as f:
    f.write(b'def')  # второй кадр
with zstd.ZstdFile('log.zst') as f:
    print(f.read(), f.mode)  # → b'abcdef' rb
# Python 3.14+
import io
from compression import zstd  # → ? нужна сборка CPython с libzstd
buf = io.BytesIO()
with zstd.ZstdFile(buf, 'w') as f:
    f.write(b'x' * 1000)
print(buf.closed, zstd.decompress(buf.getvalue()) == b'x' * 1000)  # → False True
zstd.ZstdFile(buf, 'rt')  # → ValueError: Invalid mode: 'rt'

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy