gzip --- gzip 压缩与解压缩¶
本模块允许使用 gzip 文件格式所采用的 DEFLATE 算法 对二进制数据进行压缩和解压缩。它提供了一次性的 compress()/decompress() 辅助函数,以及一个对底层文件或流对象进行封装的流式 GzipFile 包装器。
备注
请优先使用 deflate.DeflateIO 而非本模块中的函数,因为它提供了压缩和解压缩的流式接口,在向文件、套接字或流读写压缩数据时既方便又更节省内存。
可用性:
本模块默认 不包含在 OpenMV Cam 中,因为它与
deflate模块已提供的功能重复。可以从 micropython-lib(源码)安装一份副本(或将其冻结进自定义固件)。更多信息请参阅 包管理。本文档描述的就是该模块。
仅当内置的
deflate模块支持压缩时,压缩功能才可用——也就是说,在基于 STM32 的 OpenMV Cam 上不可用(参见上文其可用性说明)。
函数¶
类¶
- class gzip.GzipFile(*, fileobj, mode: str)¶
此类可用于封装一个 fileobj,它是任何 类流 对象,例如文件、套接字或流(包括
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 文档末尾 的说明。