python 3.x - Pass io.BytesIO object to gzip.GzipFile and write to GzipFile -


i want whats in documentation of gzip.gzipfile:

calling gzipfile object’s close() method not close fileobj, since might wish append more material after compressed data. allows pass io.bytesio object opened writing fileobj, , retrieve resulting memory buffer using io.bytesio object’s getvalue() method.

with normal file object works expected.

>>> import gzip >>> fileobj = open("test", "wb") >>> fileobj.writable() true >>> gzipfile = gzip.gzipfile(fileobj=fileobj) >>> gzipfile.writable() true 

but can't manage writable gzip.gzipfile object when passing io.bytesio object.

>>> import io >>> bytesbuffer = io.bytesio() >>> bytesbuffer.writable() true >>> gzipfile = gzip.gzipfile(fileobj=bytesbuffer) >>> gzipfile.writable() false 

do have open io.bytesio explicit writing, , how so? or there difference between file object returned open(filename, "wb") , object returned io.bytesio() didn't think of?

yes, need explicitly set gzipfile mode 'w'; otherwise try , take mode file object, 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 mode explicitly:

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

demo:

>>> import gzip >>> gzip.gzipfile(fileobj=io.bytesio(), mode='w').writable() true 

in principle bytesio object opened in 'w+b' mode, gzipfile @ first character of file mode.


Comments