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

5
我基本上想要做的就是文档中gzip.GzipFile所述的内容:

调用GzipFile对象的close()方法不会关闭fileobj,因为您可能希望在压缩数据之后附加更多材料。这也允许您将以写入打开的io.BytesIO对象作为fileobj,并使用io.BytesIO对象的getvalue()方法检索结果内存缓冲区。

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

>>> 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()返回的对象之间有什么区别?我没想到过吗?

1个回答

11

是的,您需要显式地将 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只会查看文件模式的第一个字符。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接