我想尝试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中都会发生。我错过了什么?
答案 0 :(得分:76)
在内存文件中写入初始文件后,您需要seek
回到文件的开头...
myio.seek(0)
答案 1 :(得分:0)
在这样的上下文中编写和读取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))