问题描述
我基本上想做gzip.GzipFile
文档中的确切内容:
I basically want to do exactly whats in the documentation of gzip.GzipFile
:
使用普通文件对象,它可以按预期工作.
With a normal file object it works as expected.
>>> import gzip
>>> fileobj = open("test", "wb")
>>> fileobj.writable()
True
>>> gzipfile = gzip.GzipFile(fileobj=fileobj)
>>> gzipfile.writable()
True
但是当传递io.BytesIO
对象时,我无法获得可写的gzip.GzipFile
对象.
But I can't manage to get a writable gzip.GzipFile
object when passing a io.BytesIO
object.
>>> import io
>>> bytesbuffer = io.BytesIO()
>>> bytesbuffer.writable()
True
>>> gzipfile = gzip.GzipFile(fileobj=bytesbuffer)
>>> gzipfile.writable()
False
我是否必须显式打开io.BytesIO
进行写作,我该怎么做?还是open(filename, "wb")
返回的文件对象和我没想到的io.BytesIO()
返回的对象之间有区别?
Do I have to open the io.BytesIO
explicit for writing, and how would I do so? Or is there a difference between a file object returned by open(filename, "wb")
and a object returned by io.BytesIO()
I didn't think of?
推荐答案
是的,您需要将GzipFile
模式显式设置为'w'
;否则它将尝试从文件对象获取模式,但是BytesIO
对象没有.mode
属性:
Yes, you need to explicitly set the GzipFile
mode to 'w'
; it would otherwise try and take the mode from the file object, but a 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'
只需明确指定模式:
gzipfile = gzip.GzipFile(fileobj=fileobj, mode='w')
演示:
>>> import gzip
>>> gzip.GzipFile(fileobj=io.BytesIO(), mode='w').writable()
True
原则上,BytesIO
对象是在'w+b'
模式下打开的,但是GzipFile
只会查看文件模式的第一个字符.
In principle a BytesIO
object is opened in 'w+b'
mode, but GzipFile
would only look at the first character of a file mode.
这篇关于将io.BytesIO对象传递给gzip.GzipFile并写入GzipFile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!