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

我想试试 python BytesIO 类。

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

from io import BytesIO
import gzip


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


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


print(result)

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

60664 次浏览

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

myio.seek(0)

How about we write and read gzip content in the same context like this?

#!/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))

myio.getvalue() is an alternative to seek that returns the bytes containing the entire contents of the buffer (docs).

It worked for me after facing a similar issue.