12.2. gzipSupport for gzip files

Source code: Lib/gzip.py


该模块提供了一个简单的界面来压缩和解压缩文件,就像GNU程序gzipgunzip一样。

数据压缩由zlib模块提供。

gzip模块提供了在Python的文件对象之后建模的GzipFile类。GzipFile类读写gzip格式文件,自动压缩或解压缩数据,使其看起来像一个普通的文件对象。

Note that additional file formats which can be decompressed by the gzip and gunzip programs, such as those produced by compress and pack, are not supported by this module.

该模块定义了以下项目:

class gzip.GzipFile([filename[, mode[, compresslevel[, fileobj[, mtime]]]]])

除了readinto()truncate()之外,GzipFile类的构造方法可以模拟文件对象的大部分方法。方法。必须给fileobjfilename中的至少一个赋予一个非平凡的值。

新的类实例基于fileobj,它可以是常规文件,StringIO对象或任何其他模拟文件的对象。它默认为None,在这种情况下打开filename以提供文件对象。

fileobj不是None时,filename参数仅用于包含在gzip文件头中,可能包括未压缩文件的原始文件名。如果可以识别,它默认为fileobj的文件名;否则,它默认为空字符串,在这种情况下,标头中不包括原始文件名。

mode参数可以是'r''rb''a''ab''w''wb',具体取决于文件是否被读取或写入。默认是fileobj的模式,如果可以看出;否则,默认值为'rb'如果没有给出,'b'标志将被添加到模式,以确保以二进制模式打开文件以实现跨平台的可移植性。

compresslevel参数是从09的整数,控制压缩级别;1最快,产生最小的压缩,而9最慢,产生最大的压缩。0没有压缩。默认值为9

mtime参数是一个可选的数字时间戳,可在压缩时写入流中。所有gzip压缩流需要包含时间戳。如果省略或None,则使用当前时间。This module ignores the timestamp when decompressing; however, some programs, such as gunzip, make use of it. The format of the timestamp is the same as that of the return value of time.time() and of the st_mtime attribute of the object returned by os.stat().

Calling a GzipFile object’s close() method does not close fileobj, since you might wish to append more material after the compressed data. This also allows you to pass a StringIO object opened for writing as fileobj, and retrieve the resulting memory buffer using the StringIO object’s getvalue() method.

GzipFile supports iteration and the with statement.

Changed in version 2.7: Support for the with statement was added.

Changed in version 2.7: Support for zero-padded files was added.

New in version 2.7: The mtime argument.

gzip.open(filename[, mode[, compresslevel]])

This is a shorthand for GzipFile(filename, mode, compresslevel). The filename argument is required; mode defaults to 'rb' and compresslevel defaults to 9.

12.2.1. Examples of usage

Example of how to read a compressed file:

import gzip
f = gzip.open('file.txt.gz', 'rb')
file_content = f.read()
f.close()

Example of how to create a compressed GZIP file:

import gzip
content = "Lots of content here"
f = gzip.open('file.txt.gz', 'wb')
f.write(content)
f.close()

Example of how to GZIP compress an existing file:

import gzip
f_in = open('file.txt', 'rb')
f_out = gzip.open('file.txt.gz', 'wb')
f_out.writelines(f_in)
f_out.close()
f_in.close()

See also

Module zlib
The basic data compression module needed to support the gzip file format.