将 io.BytesIO 对象传递给 gzip.GzipFile 并写入 GzipFile

Pass io.BytesIO object to gzip.GzipFile and write to GzipFile

我基本上想做 gzip.GzipFile 文档中的内容:

Calling a GzipFile object’s close() method does not close fileobj, since you might wish to append more material after the compressed data. This also allows you to pass a io.BytesIO object opened for writing as fileobj, and retrieve the resulting memory buffer using the io.BytesIO object’s getvalue() method.

对于普通文件对象,它按预期工作。

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

但是我无法在传递 io.BytesIO 对象时获得可写的 gzip.GzipFile 对象。

>>> import io
>>> bytesbuffer = io.BytesIO()
>>> bytesbuffer.writable()
True
>>> gzipfile = gzip.GzipFile(fileobj=bytesbuffer)
>>> gzipfile.writable()
False

我是否必须打开 io.BytesIO 显式进行写入,我该怎么做?还是我没想到open(filename, "wb")返回的文件对象和io.BytesIO()返回的对象有区别?

是的,您需要将 GzipFile 模式显式设置为 'w';否则它会尝试从文件对象中获取模式,但是 BytesIO 对象没有 .mode 属性:

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

只需明确指定模式:

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

演示:

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

原则上 BytesIO 对象以 'w+b' 模式打开,但 GzipFile 只会查看文件模式的第一个字符。