I need to read binary data from some files that are normally compressed with gzip. I have managed to read the data by using the gzip module:
def decode(self, filename):
with gzip.open(filename, 'rb') as f:
# ReadData
However sometimes the files are not compressed in which case I get an IOError (because the file does not have the gzip header).
I could do something like:
try:
f = gzip.open(filename, 'rb')
f._read_gzip_header()
f.rewind()
except IOError:
f.close()
f = open(filename, 'rb')
with f as gz:
#ReadData
but I don't feel it is a good way to fix it.
I am looking for an elegant solution to solve this problem. I will write several "decode" functions for several file types. The solution I consider are to create a subclass of the GzipFile to deal with it but I believe there might be better ways.
I am using Python 2.7
Thank you in advance for any suggestion!