写入然后读取内存字节(BytesIO)会得到空白结果 [英] Writing then reading in-memory bytes (BytesIO) gives a blank result

查看:99
本文介绍了写入然后读取内存字节(BytesIO)会得到空白结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想尝试python BytesIO类。

I wanted to try out the python BytesIO class.

作为一个实验,我尝试写入内存中的zip文件,然后从中读取字节压缩文件。因此,我没有传递文件对象到 gzip ,而是传递了 BytesIO 对象。这是整个脚本:

As an experiment I tried writing to a zip file in memory, and then reading the bytes back out of that zip file. So instead of passing in a file-object to gzip, I pass in a BytesIO object. Here is the entire script:

from io import BytesIO
import gzip

# write bytes to zip file in memory
myio = BytesIO()
g = gzip.GzipFile(fileobj=myio, mode='wb')
g.write(b"does it work")
g.close()

# read bytes from zip file in memory
g = gzip.GzipFile(fileobj=myio, mode='rb')
result = g.read()
g.close()

print(result)

但是它返回一个空的 bytes 对象,以获取结果。在Python 2.7和3.4中都会发生这种情况。我缺少什么?

But it is returning an empty bytes object for result. This happens in both Python 2.7 and 3.4. What am I missing?

推荐答案

您需要 seek 回到文件的开头...

You need to seek back to the beginning of the file after writing the initial in memory file...

myio.seek(0)

这篇关于写入然后读取内存字节(BytesIO)会得到空白结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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