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?
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.
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.
You need to seek
back to the beginning of the file after writing the initial in memory file...
myio.seek(0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With