Binary buffer in Python

jelovirt picture jelovirt · Aug 24, 2008 · Viewed 54.5k times · Source

In Python you can use StringIO for a file-like buffer for character data. Memory-mapped file basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is intended for binary data and is memory only, equivalent to Java's ByteArrayOutputStream?

The use-case I have is I want to create a ZIP file in memory, and ZipFile requires a file-like object.

Answer

akhan picture akhan · Sep 9, 2011

You are probably looking for io.BytesIO class. It works exactly like StringIO except that it supports binary data:

from io import BytesIO
bio = BytesIO(b"some initial binary data: \x00\x01")

StringIO will throw TypeError:

from io import StringIO
sio = StringIO(b"some initial binary data: \x00\x01")