all Python 3gzipterm
gzip.GzipFile
gzip files
A wrapper class around a binary file object that compresses or decompresses gzip on the fly.
Syntax
gzip.GzipFile(filename=None, mode=None, compresslevel=6, fileobj=None, mtime=None)
Use it when the compressed stream lives not in a file on disk but in a BytesIO, a socket or someone else's open file; for plain files gzip.open() is simpler. The gzip trailer (CRC and size) is written only on close(): calling getvalue() on the BytesIO before the GzipFile is closed gives truncated data. Closing the GzipFile does not close the fileobj you passed. Pass mode explicitly: writing without mode is deprecated since 3.9. Since 3.15 the default compression level is 6, not 9: compression is faster and the archive slightly larger; pass compresslevel=9 explicitly to keep the old size.
Examples
import gzip, io
buf = io.BytesIO()
g = gzip.GzipFile(fileobj=buf, mode='wb')
g.write(b'x' * 100)
try:
gzip.decompress(buf.getvalue())
except EOFError:
print('хвост ещё не записан') # → хвост ещё не записан
g.close()
print(gzip.decompress(buf.getvalue())[:3], buf.closed) # → b'xxx' False
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy