gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:18:07 24 4
gpt4 key购买 nike

我基本上想完全按照 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com