# `zlib` --- 与 gzip 兼容的压缩

For applications that require data compression, the functions in this module allow compression and decompression, using the zlib library. The zlib library has its own home page at https://www.zlib.net. There are known incompatibilities between the Python module and versions of the zlib library earlier than 1.1.3; 1.1.3 has a security vulnerability, so we recommend using 1.1.4 or later.

zlib 的函数有很多选项，一般需要按特定顺序使用。本文档没有覆盖全部的用法。更多详细信息请于 http://www.zlib.net/manual.html 参阅官方手册。

要读写 `.gz` 格式的文件，请参考 `gzip` 模块。

此模块中可用的异常和函数如下：

exception `zlib.``error`

  在压缩或解压缩过程中发生错误时的异常。

`zlib.``adler32`(data[, value])

  计算 data 的 Adler-32 校验值。(Adler-32 校验的可靠性与 CRC32 基本相当，但比计算 CRC32 更高效。) 计算的结果是一个 32 位的整数。参数 value 是校验时的起始值，其默认值为 1。借助参数 value 可为分段的输入计算校验值。此算法没有加密强度，不应用于身份验证和数字签名。此算法的目的仅为验证数据的正确性，不适合作为通用散列算法。

  在 3.0 版更改: 返回值永远是无符号数。要在所有的 Python 版本和平台上获得相同的值，请使用 `adler32(data) & 0xffffffff`。

`zlib.``compress`(data, /, level=-1)

  压缩 data 中的字节，返回含有已压缩内容的 bytes 对象。参数 level 为整数，可取值为 `0` 到 `9` 或 `-1`，用于指定压缩等级。`1` (Z_BEST_SPEED) 表示最快速度和最低压缩率，`9` (Z_BEST_COMPRESSION) 表示最慢速度和最高压缩率。`0` (Z_NO_COMPRESSION) 表示不压缩。参数默认值为 `-1` (Z_DEFAULT_COMPRESSION)。Z_DEFAULT_COMPRESSION 是速度和压缩率之间的平衡 (一般相当于设压缩等级为 6)。函数发生错误时抛出 `error` 异常。

  在 3.6 版更改: 现在，level 可作为关键字参数。

`zlib.``compressobj`(level=-1, method=DEFLATED, wbits=MAX_WBITS, memLevel=DEF_MEM_LEVEL, strategy=Z_DEFAULT_STRATEGY[, zdict])

  返回一个 压缩对象，用来压缩内存中难以容下的数据流。

  参数 level 为压缩等级，是整数，可取值为 `0` 到 `9` 或 `-1`。`1` (Z_BEST_SPEED) 表示最快速度和最低压缩率，`9` (Z_BEST_COMPRESSION) 表示最慢速度和最高压缩率。`0` (Z_NO_COMPRESSION) 表示不压缩。参数默认值为 `-1` (Z_DEFAULT_COMPRESSION)。Z_DEFAULT_COMPRESSION 是速度和压缩率之间的平衡 (一般相当于设压缩等级为 6)。

  method 表示压缩算法。现在只支持 `DEFLATED` 这个算法。

  参数 wbits 指定压缩数据时所使用的历史缓冲区的大小 (窗口大小)，并指定压缩输出是否包含头部或尾部。参数的默认值是 `15` (MAX_WBITS)。参数的值分为几个范围：

  - +9 到 +15：窗口大小以 2 为底的对数。即这些值对应着 512 到 32768 的窗口大小。更大的值会提供更好的压缩，同时内存开销也会更大。压缩输出会包含 zlib 特定格式的头部和尾部。

  - −9 到 −15：绝对值为窗口大小以 2 为底的对数。压缩输出仅包含压缩数据，没有头部和尾部。

  - +25 到 +31 = 16 + (9 到 15)：后 4 个比特位为窗口大小以 2 为底的对数。压缩输出包含一个基本的 gzip 头部，并以校验和为尾部。

  参数 memLevel 指定内部压缩操作时所占用内存大小。参数取 `1` 到 `9`。更大的值占用更多的内存，同时速度也更快输出也更小。

  参数 strategy 用于调节压缩算法。可取值为 `Z_DEFAULT_STRATEGY`、`Z_FILTERED`、`Z_HUFFMAN_ONLY`、`Z_RLE` (zlib 1.2.0.1) 或 `Z_FIXED` (zlib 1.2.2.2)。

  参数 zdict 指定预定义的压缩字典。它是一个字节序列 (如 `bytes` 对象)，其中包含用户认为要压缩的数据中可能频繁出现的子序列。频率高的子序列应当放在字典的尾部。

  在 3.3 版更改: 添加关键字参数 zdict。

`zlib.``crc32`(data[, value])

  计算 data 的 CRC (循环冗余校验) 值。计算的结果是一个 32 位的整数。参数 value 是校验时的起始值，其默认值为 0。借助参数 value 可为分段的输入计算校验值。此算法没有加密强度，不应用于身份验证和数字签名。此算法的目的仅为验证数据的正确性，不适合作为通用散列算法。

  在 3.0 版更改: 返回值永远是无符号数。要在所有的 Python 版本和平台上获得相同的值，请使用 `crc32(data) & 0xffffffff`。

`zlib.``decompress`(data, /, wbits=MAX_WBITS, bufsize=DEF_BUF_SIZE)

  解压 data 中的字节，返回含有已解压内容的 bytes 对象。参数 wbits 取决于 data 的格式，具体参见下边的说明。bufsize 为输出缓冲区的起始大小。函数发生错误时抛出 `error` 异常。

  The wbits parameter controls the size of the history buffer (or "window size"), and what header and trailer format is expected. It is similar to the parameter for `compressobj()`, but accepts more ranges of values:

  - +8 to +15: The base-two logarithm of the window size. The input must include a zlib header and trailer.

  - 0: Automatically determine the window size from the zlib header. Only supported since zlib 1.2.3.5.

  - −8 to −15: Uses the absolute value of wbits as the window size logarithm. The input must be a raw stream with no header or trailer.

  - +24 to +31 = 16 + (8 to 15): Uses the low 4 bits of the value as the window size logarithm. The input must include a gzip header and trailer.

  - +40 to +47 = 32 + (8 to 15): Uses the low 4 bits of the value as the window size logarithm, and automatically accepts either the zlib or gzip format.

  When decompressing a stream, the window size must not be smaller than the size originally used to compress the stream; using a too-small value may result in an `error` exception. The default wbits value corresponds to the largest window size and requires a zlib header and trailer to be included.

  bufsize is the initial size of the buffer used to hold decompressed data. If more space is required, the buffer size will be increased as needed, so you don't have to get this value exactly right; tuning it will only save a few calls to `malloc()`.

  在 3.6 版更改: wbits and bufsize can be used as keyword arguments.

`zlib.``decompressobj`(wbits=MAX_WBITS[, zdict])

  Returns a decompression object, to be used for decompressing data streams that won't fit into memory at once.

  The wbits parameter controls the size of the history buffer (or the "window size"), and what header and trailer format is expected. It has the same meaning as described for decompress().

  The zdict parameter specifies a predefined compression dictionary. If provided, this must be the same dictionary as was used by the compressor that produced the data that is to be decompressed.

  注解

  If zdict is a mutable object (such as a `bytearray`), you must not modify its contents between the call to `decompressobj()` and the first call to the decompressor's `decompress()` method.

  在 3.3 版更改: Added the zdict parameter.

压缩对象支持以下方法：

`Compress.``compress`(data)

  压缩 data 并返回 bytes 对象，这个对象含有 data 的部分或全部内容的已压缩数据。所得的对象必须拼接在上一次调用 `compress()` 方法所得数据的后面。缓冲区中可能留存部分输入以供下一次调用。

`Compress.``flush`([mode])

  压缩所有缓冲区的数据并返回已压缩的数据。参数 mode 可以传入的常量为：`Z_NO_FLUSH`、`Z_PARTIAL_FLUSH`、`Z_SYNC_FLUSH`、`Z_FULL_FLUSH`、`Z_BLOCK` (zlib 1.2.3.4) 或 `Z_FINISH`。默认值为 `Z_FINISH`。`Z_FINISH` 关闭已压缩数据流并不允许再压缩其他数据，`Z_FINISH` 以外的值皆允许这个对象继续压缩数据。调用 `flush()` 方法并将 mode 设为 `Z_FINISH` 后会无法再次调用 `compress()`，此时只能删除这个对象。

`Compress.``copy`()

  返回此压缩对象的一个拷贝。它可以用来高效压缩一系列拥有相同前缀的数据。

在 3.8 版更改: Added `copy.copy()` and `copy.deepcopy()` support to compression objects.

解压缩对象支持以下方法：

`Decompress.``unused_data`

  A bytes object which contains any bytes past the end of the compressed data. That is, this remains `b""` until the last byte that contains compression data is available. If the whole bytestring turned out to contain compressed data, this is `b""`, an empty bytes object.

`Decompress.``unconsumed_tail`

  A bytes object that contains any data that was not consumed by the last `decompress()` call because it exceeded the limit for the uncompressed data buffer. This data has not yet been seen by the zlib machinery, so you must feed it (possibly with further data concatenated to it) back to a subsequent `decompress()` method call in order to get correct output.

`Decompress.``eof`

  A boolean indicating whether the end of the compressed data stream has been reached.

  This makes it possible to distinguish between a properly-formed compressed stream, and an incomplete or truncated one.

  3.3 新版功能.

`Decompress.``decompress`(data, max_length=0)

  Decompress data, returning a bytes object containing the uncompressed data corresponding to at least part of the data in string. This data should be concatenated to the output produced by any preceding calls to the `decompress()` method. Some of the input data may be preserved in internal buffers for later processing.

  If the optional parameter max_length is non-zero then the return value will be no longer than max_length. This may mean that not all of the compressed input can be processed; and unconsumed data will be stored in the attribute `unconsumed_tail`. This bytestring must be passed to a subsequent call to `decompress()` if decompression is to continue. If max_length is zero then the whole input is decompressed, and `unconsumed_tail` is empty.

  在 3.6 版更改: max_length can be used as a keyword argument.

`Decompress.``flush`([length])

  All pending input is processed, and a bytes object containing the remaining uncompressed output is returned. After calling `flush()`, the `decompress()` method cannot be called again; the only realistic action is to delete the object.

  The optional parameter length sets the initial size of the output buffer.

`Decompress.``copy`()

  Returns a copy of the decompression object. This can be used to save the state of the decompressor midway through the data stream in order to speed up random seeks into the stream at a future point.

在 3.8 版更改: Added `copy.copy()` and `copy.deepcopy()` support to decompression objects.

通过下列常量可获取模块所使用的 zlib 库的版本信息：

`zlib.``ZLIB_VERSION`

  构建此模块时所用的 zlib 库的版本字符串。它的值可能与运行时所加载的 zlib 不同。运行时加载的 zlib 库的版本字符串为 `ZLIB_RUNTIME_VERSION`。

`zlib.``ZLIB_RUNTIME_VERSION`

  解释器所加载的 zlib 库的版本字符串。

  3.3 新版功能.

参见

模块 `gzip`

  读写 gzip 格式的文件。

http://www.zlib.net

  zlib 库项目主页。

http://www.zlib.net/manual.html

  zlib 库用户手册。提供了库的许多功能的解释和用法。