# 12.1. `zlib` — 与 gzip 兼容的压缩

此模块为需要数据压缩的程序提供了一系列函数，用于压缩和解压缩。这些函数使用了 zlib 库。zlib 库的项目主页是 http://www.zlib.net. 版本低于 1.1.3 的 zlib 与此 Python 模块之间存在已知的不兼容。1.1.3 版本的 zlib 存在一个安全漏洞，我们推荐使用 1.1.4 或更新的版本。

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

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

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

exception `zlib.``error`

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

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

  Computes an Adler-32 checksum of data. (An Adler-32 checksum is almost as reliable as a CRC32 but can be computed much more quickly.) If value is present, it is used as the starting value of the checksum; otherwise, a fixed default value is used. This allows computing a running checksum over the concatenation of several inputs. The algorithm is not cryptographically strong, and should not be used for authentication or digital signatures. Since the algorithm is designed for use as a checksum algorithm, it is not suitable for use as a general hash algorithm.

  This function always returns an integer object.

注解

To generate the same numeric value across all Python versions and platforms use adler32(data) & 0xffffffff. If you are only using the checksum in packed binary format this is not necessary as the return value is the correct 32bit binary representation regardless of sign.

在 2.6 版更改: The return value is in the range [-2**31, 2**31-1] regardless of platform. In older versions the value is signed on some platforms and unsigned on others.

在 3.0 版更改: The return value is unsigned and in the range [0, 2**32-1] regardless of platform.

`zlib.``compress`(string[, level])

  Compresses the data in string, returning a string contained compressed data. level is an integer from `0` to `9` controlling the level of compression; `1` is fastest and produces the least compression, `9` is slowest and produces the most. `0` is no compression. The default value is `6`. Raises the `error` exception if any error occurs.

`zlib.``compressobj`([level[, method[, wbits[, memlevel[, strategy]]]]])

  Returns a compression object, to be used for compressing data streams that won’t fit into memory at once. level is an integer from `0` to `9` or `-1`, controlling the level of compression; `1` is fastest and produces the least compression, `9` is slowest and produces the most. `0` is no compression. The default value is `-1` (Z_DEFAULT_COMPRESSION). Z_DEFAULT_COMPRESSION represents a default compromise between speed and compression (currently equivalent to level 6).

  method is the compression algorithm. Currently, the only supported value is `DEFLATED`.

  The wbits argument controls the size of the history buffer (or the “window size”) used when compressing data, and whether a header and trailer is included in the output. It can take several ranges of values. The default is 15.

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

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

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

  memlevel controls the amount of memory used for internal compression state. Valid values range from `1` to `9`. Higher values using more memory, but are faster and produce smaller output. The default is 8.

  strategy is used to tune the compression algorithm. Possible values are `Z_DEFAULT_STRATEGY`, `Z_FILTERED`, and `Z_HUFFMAN_ONLY`. The default is `Z_DEFAULT_STRATEGY`.

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

  Computes a CRC (Cyclic Redundancy Check) checksum of data. If value is present, it is used as the starting value of the checksum; otherwise, a fixed default value is used. This allows computing a running checksum over the concatenation of several inputs. The algorithm is not cryptographically strong, and should not be used for authentication or digital signatures. Since the algorithm is designed for use as a checksum algorithm, it is not suitable for use as a general hash algorithm.

  This function always returns an integer object.

注解

To generate the same numeric value across all Python versions and platforms use crc32(data) & 0xffffffff. If you are only using the checksum in packed binary format this is not necessary as the return value is the correct 32bit binary representation regardless of sign.

在 2.6 版更改: The return value is in the range [-2**31, 2**31-1] regardless of platform. In older versions the value would be signed on some platforms and unsigned on others.

在 3.0 版更改: The return value is unsigned and in the range [0, 2**32-1] regardless of platform.

`zlib.``decompress`(string[, wbits[, bufsize]])

  Decompresses the data in string, returning a string containing the uncompressed data. The wbits parameter depends on the format of string, and is discussed further below. If bufsize is given, it is used as the initial size of the output buffer. Raises the `error` exception if any error occurs.

  wbits 形参控制历史缓冲区（或称“窗口尺寸”）的大小以及所期望的头部和尾部格式。 它类似于 `compressobj()` 的形参，但可接受更大范围的值：

  - +8 至 +15：窗口尺寸以二为底的对数。 输入必须包含 zlib 头部和尾部。

  - 0：根据 zlib 头部自动确定窗口大小。 只从 zlib 1.2.3.5 版起受支持。

  - −8 to −15：使用 wbits 的绝对值作为窗口大小以二为底的对数。 输入必须为原始数据流，没有头部和尾部。

  - +24 至 +31 = 16 + (8 至 15)：使用后 4 个比特位作为窗口大小以二为底的对数。 输入必须包括 gzip 头部和尾部。

  - +40 至 +47 = 32 + (8 至 15)：使用后 4 个比特位作为窗口大小以二为底的对数，并且自动接受 zlib 或 gzip 格式。

  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 is 15, which 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()`. The default size is 16384.

`zlib.``decompressobj`([wbits])

  返回一个解压对象，用来解压无法被一次性放入内存的数据流。

  wbits 形参控制历史缓冲区的大小（或称“窗口大小”）以及所期望的头部和尾部格式。 它的含义与 对 decompress() 的描述 相同。

压缩对象支持以下方法：

`Compress.``compress`(string)

  Compress string, returning a string containing compressed data for at least part of the data in string. This data should be concatenated to the output produced by any preceding calls to the `compress()` method. Some input may be kept in internal buffers for later processing.

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

  All pending input is processed, and a string containing the remaining compressed output is returned. mode can be selected from the constants `Z_SYNC_FLUSH`, `Z_FULL_FLUSH`, or `Z_FINISH`, defaulting to `Z_FINISH`. `Z_SYNC_FLUSH` and `Z_FULL_FLUSH` allow compressing further strings of data, while `Z_FINISH` finishes the compressed stream and prevents compressing any more data. After calling `flush()` with mode set to `Z_FINISH`, the `compress()` method cannot be called again; the only realistic action is to delete the object.

`Compress.``copy`()

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

  2.5 新版功能.

Decompression objects support the following methods, and two attributes:

`Decompress.``unused_data`

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

  The only way to determine where a string of compressed data ends is by actually decompressing it. This means that when compressed data is contained part of a larger file, you can only find the end of it by reading data and feeding it followed by some non-empty string into a decompression object’s `decompress()` method until the `unused_data` attribute is no longer the empty string.

`Decompress.``unconsumed_tail`

  A string 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.``decompress`(string[, max_length])

  Decompress string, returning a string 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 string must be passed to a subsequent call to `decompress()` if decompression is to continue. If max_length is not supplied then the whole input is decompressed, and `unconsumed_tail` is an empty string.

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

  All pending input is processed, and a string 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.

  可选的形参 length 设置输出缓冲区的初始大小。

`Decompress.``copy`()

  返回解压缩对象的一个拷贝。 它可以用来在数据流的中途保存解压缩器的状态以便加快随机查找数据流后续位置的速度。

  2.5 新版功能.

参见

模块 `gzip`

  读写 gzip 格式的文件。

http://www.zlib.net

  zlib 库项目主页。

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

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