python-3.x - 将 io.BytesIO 对象传递给 gzip.GzipFile 并写入 GzipFile

标签 python-3.x gzip bytesio

我基本上想完全按照 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 只会查看 a 的第一个字 rune 件模式。

关于python-3.x - 将 io.BytesIO 对象传递给 gzip.GzipFile 并写入 GzipFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32794837/

相关文章:

python - 在 python3 中写入 csv 中的 io.BytesIO 失败

python - 如何从生成器读取 tarfile?

python - 需要计算时间戳之间的时间差并将其存储在变量中

algorithm - 为什么我不能遍历数据框中的新列?

python - 按文件数拆分 gzip 文件

node.js - http响应的Gzip解压

python gzipped fileinput 返回二进制字符串而不是文本字符串

python - Pandas:在数据框中每隔第二行插入一个空行

python - 即使在Macintosh上安装了GhostScript,Python <没有这样的文件或目录:'gs'>错误*问题仍然存在!*

python - Discord 使用 BytesIO 发送空白文本文件