Python 3.8+gzipexception
gzip.BadGzipFile
exceptions
The gzip exception for data that is not gzip or is corrupt (a wrong header or CRC).
Syntax
except gzip.BadGzipFile:
It derives from OSError, so except OSError catches it too — unlike zipfile.BadZipFile. gzip.open() does not check the file: the error surfaces on the first read(). A truncated archive gives EOFError rather than BadGzipFile, while a checksum mismatch raises BadGzipFile with the message 'CRC check failed'.
Examples
import gzip
with open('plain.txt', 'wb') as f:
f.write(b'just text')
f = gzip.open('plain.txt')
try:
f.read()
except gzip.BadGzipFile as e:
print(e) # → Not a gzipped file (b'ju')
finally:
f.close()
print(issubclass(gzip.BadGzipFile, OSError)) # → True
See also
Open in the full glossarydocs.python.orgReport an inaccuracy