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

twa*_*lig 56 python byte gzip bytesio

我想尝试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)
Run Code Online (Sandbox Code Playgroud)

但它正在返回一个空bytes对象result.这在Python 2.7和3.4中都会发生.我错过了什么?

mgi*_*son 91

seek在内存文件中写入初始文件后,您需要回到文件的开头...

myio.seek(0)
Run Code Online (Sandbox Code Playgroud)

  • 由matplotlib savefig()填充的缓冲区在应用程序服务器发送之前也需要这样做.感谢结束了几个小时的研究! (4认同)
  • 或者使用“getvalue()”。这些小东西散得到处都是! (2认同)

Gat*_*Lee 6

我们在这样的上下文中编写和读取 gzip 内容怎么样?

#!/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)
    gzipped_content = myio.getvalue()

print(gzipped_content)
print(content == gzip.decompress(gzipped_content))
Run Code Online (Sandbox Code Playgroud)

  • 我认为这里不需要`g.close()`,对吧? (2认同)