gzip – gzip 压缩与解压缩¶
This module implements a subset of the corresponding CPython module,
as described below. For more information, refer to the original
CPython documentation: gzip。
此模块允许使用 gzip 文件格式采用的 DEFLATE算法 对二进制数据进行压缩和解压缩。
备注
优先使用 deflate.DeflateIO,而不是本模块中的函数,因为它提供了对压缩和解压缩的流接口,当处理读取或写入压缩数据到文件、套接字或流时更方便且更节省内存。
可用性:
- 此模块 默认不包含 在官方 MicroPython 固件发布中,因为它复制了 - deflate模块中可用的功能。
- 此模块的副本可以从 micropython-lib ( source )安装(或冻结)。有关更多信息,请参阅 包管理。本文档描述了该模块。 
- 只有在内置的 - deflate模块中启用了压缩支持时,才能使用压缩支持。
函数¶
- gzip.decompress(data, /)¶
- 将 data 解压缩为一个字节对象。 
- gzip.compress(data, /)¶
- 将 data 压缩为一个字节对象。 
类¶
- class gzip.GzipFile(*, fileobj, mode)¶
- 此类可用于包装一个 fileobj ,它是任何 stream-like 对象,例如文件、套接字或流(包括 - io.BytesIO)。它本身就是一个流,并实现了标准的 read/readinto/write/close 方法。- 当 mode 参数为 - "rb"时,从 GzipFile 实例读取将会解压缩底层流中的数据并返回解压缩后的数据。- 如果启用了压缩支持,则 mode 参数可以设置为 - "wb",并且对 GzipFile 实例的写入将被压缩并写入底层流。- 默认情况下,GzipFile 类将使用 gzip 文件格式读取和写入数据,包括带有校验和的页眉和页脚以及 512 字节的窗口大小。 - file、compresslevel 和 mtime 参数不受支持。必须始终指定 fileobj 和 mode 作为关键字参数。 
示例¶
gzip.GzipFile 的典型用例是从存储中读取或写入一个压缩文件:
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)
有关使用 gzip 源和选择窗口大小的指导,请参阅 deflate 文档末尾的注意事项。