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

twasbrillig picture twasbrillig · Nov 12, 2014 · Viewed 33.8k times · Source

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?

Answer

mgilson picture mgilson · Nov 12, 2014

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

myio.seek(0)