Writing then reading in-memory bytes (BytesIO) gives a blank result

冷暖自知 提交于 2019-11-27 12:54:02

问题


I wanted to try out the python BytesIO class.

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 BytesIO object. Here is the entire script:

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 bytes object for result. This happens in both Python 2.7 and 3.4. What am I missing?


回答1:


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

myio.seek(0)



回答2:


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?

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


来源:https://stackoverflow.com/questions/26879981/writing-then-reading-in-memory-bytes-bytesio-gives-a-blank-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!