Skip to content Skip to sidebar Skip to footer

Pass Io.bytesio Object To Gzip.gzipfile And Write To Gzipfile

I basically want to do exactly whats in the documentation of gzip.GzipFile: Calling a GzipFile object’s close() method does not close fileobj, since you might wish to append mor

Solution 1:

Yes, you need to explicitly set the GzipFile mode to 'w'; it would otherwise try and take the mode from the file object, but a BytesIO object has no .mode attribute:

>>> import io
>>> io.BytesIO().mode
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: '_io.BytesIO'object has no attribute 'mode'

Just specify the mode explicitly:

gzipfile = gzip.GzipFile(fileobj=fileobj, mode='w')

Demo:

>>>import gzip>>>gzip.GzipFile(fileobj=io.BytesIO(), mode='w').writable()
True

In principle a BytesIO object is opened in 'w+b' mode, but GzipFile would only look at the first character of a file mode.

Post a Comment for "Pass Io.bytesio Object To Gzip.gzipfile And Write To Gzipfile"