all Python 3gzipterm
gzip
module
Reading and writing .gz files and compressing bytes in memory in the same format as the gzip and gunzip tools.
Syntax
import gzip
Use gzip for a single compressed stream: logs, data dumps, HTTP responses. An archive of many files is zipfile or tarfile, and a raw stream without the gzip header is zlib. gzip.open() opens in binary mode by default and returns bytes; for text use mode 'rt' or 'wt' and an encoding.
Examples
import gzip
data = b'abc' * 1000
print(len(gzip.compress(data)) < len(data)) # → True
with gzip.open('log.txt.gz', 'wt', encoding='utf-8') as f:
f.write('привет\n')
with gzip.open('log.txt.gz', 'rt', encoding='utf-8') as f:
print(f.read().strip()) # → привет
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy