99

我想试试 python BytesIO 类。

作为一个实验,我尝试写入内存中的 zip 文件,然后从该 zip 文件中读取字节。因此,我没有将文件对象传递给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)

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

4

2 回答 2

175

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

myio.seek(0)
于 2014-11-12T05:40:40.347 回答
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))
于 2019-06-26T16:21:44.737 回答