Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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() with gzip.GzipFile(fileobj=myio, mode='wb') as g:     g.write(b"does it work")  # read bytes from zip file in memory with gzip.GzipFile(fileobj=myio, mode='rb') as g:     result = g.read()  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?

like image 931
twasbrillig Avatar asked Nov 12 '14 05:11

twasbrillig


People also ask

What does BytesIO do python?

StringIO and BytesIO are methods that manipulate string and bytes data in memory. StringIO is used for string data and BytesIO is used for binary data. This classes create file like object that operate on string data. The StringIO and BytesIO classes are most useful in scenarios where you need to mimic a normal file.

How do I save a BytesIO file in Python?

First, open a file in binary write mode and then specify the contents to write in the form of bytes. Next, use the write function to write the byte contents to a binary file.


1 Answers

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

myio.seek(0) 
like image 84
mgilson Avatar answered Oct 19 '22 08:10

mgilson