gzip – gzip compression & decompression — MicroPython latest documentation (original) (raw)

This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions.

If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version.

This module implements a subset of the corresponding CPython module, as described below. For more information, refer to the original CPython documentation: gzip.

This module allows compression and decompression of binary data with theDEFLATE algorithm used by the gzip file format.

Note

Prefer to use deflate.DeflateIO instead of the functions in this module as it provides a streaming interface to compression and decompression which is convenient and more memory efficient when working with reading or writing compressed data to a file, socket, or stream.

Availability:

Functions

gzip.open(filename, mode, /)

Wrapper around built-in open() returning a GzipFile instance.

gzip.decompress(data, /)

Decompresses data into a bytes object.

gzip.compress(data, /)

Compresses data into a bytes object.

Classes

class gzip.GzipFile(*, fileobj, mode)

This class can be used to wrap a fileobj which is anystream-like object such as a file, socket, or stream (including io.BytesIO). It is itself a stream and implements the standard read/readinto/write/close methods.

When the mode argument is "rb", reads from the GzipFile instance will decompress the data in the underlying stream and return decompressed data.

If compression support is enabled then the mode argument can be set to"wb", and writes to the GzipFile instance will be compressed and written to the underlying stream.

By default the GzipFile class will read and write data using the gzip file format, including a header and footer with checksum and a window size of 512 bytes.

The file, compresslevel, and mtime arguments are not supported. fileobj and mode must always be specified as keyword arguments.

Examples

A typical use case for gzip.GzipFile is to read or write a compressed file from storage:

import gzip

Reading:

with open("data.gz", "rb") as f: with gzip.GzipFile(fileobj=f, mode="rb") as g: # Use g.read(), g.readinto(), etc.

Same, but using gzip.open:

with gzip.open("data.gz", "rb") as f: # Use f.read(), f.readinto(), etc.

Writing:

with open("data.gz", "wb") as f: with gzip.GzipFile(fileobj=f, mode="wb") as g: # Use g.write(...) etc

Same, but using gzip.open:

with gzip.open("data.gz", "wb") as f: # Use f.write(...) etc

Write a dictionary as JSON in gzip format, with a

small (64 byte) window size.

config = { ... } with gzip.open("config.gz", "wb") as f: json.dump(config, f)

For guidance on working with gzip sources and choosing the window size see the note at the end of the deflate documentation.