写入然后读取内存字节(BytesIO)会得到空白结果


74

我想尝试python BytesIO类。

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

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对象result。在Python 2.7和3.4中都会发生这种情况。我想念什么?

Answers:


132

seek在将初始文件写入内存文件后,您需要返回文件的开头。

myio.seek(0)

7
由matplotlib savefig()填充的缓冲区在需要由应用程序服务器发送之前也确实需要这样做。感谢您结束研究时间!
TomTom101 '17

我来了,我看到了,竖起大拇指。(两个月后)我来了,我看到了,我想再次竖起大拇指!
theaws.blog

1
或使用getvalue()。这些小东西散落在各处!
theaws.blog

的GetValue()没有工作对我来说除了寻求(0)
CAOT

2

我们在这样的上下文中读写gzip内容怎么样?如果这种方法不错,并且适合您阅读此书的任何人,请对此答案+1,这样我就知道这种方法对其他人有用吗?

#!/usr/bin/env python

from io import BytesIO
import gzip

content = b"does it work"

# write bytes to zip file in memory
gzipped_content = None
with BytesIO() as myio:
    with gzip.GzipFile(fileobj=myio, mode='wb') as g:
        g.write(content)
        g.close()
    gzipped_content = myio.getvalue()

print(gzipped_content)
print(content == gzip.decompress(gzipped_content))
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.