写入然后读取内存字节(BytesIO)会产生一个空白的resu

2024-05-08 11:35:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我想试试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)

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


Tags: 文件对象infromimportbytesresultzip
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))

在写入初始内存文件后,您需要^{}返回到文件的开头。。。

myio.seek(0)

相关问题 更多 >

    热门问题