Python 写入然后读取内存字节 (BytesIO) 给出空白结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26879981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing then reading in-memory bytes (BytesIO) gives a blank result
提问by twasbrillig
I wanted to try out the python BytesIO class.
我想试用 python BytesIO 类。
As an experiment I tried writing to a zip file in memory, and then reading the bytes back out of that zip file. So instead of passing in a file-object to gzip, I pass in a BytesIOobject. Here is the entire script:
作为实验,我尝试写入内存中的 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)
But it is returning an empty bytesobject for result. This happens in both Python 2.7 and 3.4. What am I missing?
但它为 返回一个空bytes对象result。这发生在 Python 2.7 和 3.4 中。我错过了什么?
采纳答案by mgilson
回答by Gatsby Lee
How about we write and read gzip content in the same context like this? If this approach is good and works for you anyone reading this, please +1 for this answer so that I know this approach right and works for other people?
我们在这样的上下文中编写和读取 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))

