将io.BytesIO对象传递给gzip.GzipFile并写入GzipFile [英] Pass io.BytesIO object to gzip.GzipFile and write to GzipFile

查看:553
本文介绍了将io.BytesIO对象传递给gzip.GzipFile并写入GzipFile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I basically want to do exactly whats in the documentation of gzip.GzipFile:

调用GzipFile对象的close()方法不会关闭fileobj,因为您可能希望在压缩数据后追加更多内容.这也使您可以传递一个打开的io.BytesIO对象以作为fileobj进行写操作,并使用io.BytesIO对象的getvalue()方法检索所得的内存缓冲区.

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.

使用普通文件对象,它可以按预期工作.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆