all Python 3ioterm
io.BytesIO
bytes
A file-like object for binary data held in memory. The counterpart of StringIO for bytes.
Syntax
io.BytesIO(initial_bytes=b'')
The usual trap: after write() the position sits at the end, so a following read() gives you b'' unless you seek(0) first, whereas getvalue() returns the whole buffer regardless of position. Reach for it when some library insists on a file object but you would rather keep the data in memory, for instance building a zip archive or an image without touching the disk. Once the object is closed the buffer is discarded and getvalue() raises ValueError, so grab the bytes before closing.
Examples
import io
buf = io.BytesIO()
buf.write(b'\x00\x01\x02')
buf.getvalue() # → b'\x00\x01\x02'
buf.seek(0)
buf.read(1) # → b'\x00'
b = io.BytesIO(b'data')
b.read() # → b'data'
len(io.BytesIO(b'abc').getvalue()) # → 3
See also
Open in the full glossarydocs.python.orgReport an inaccuracy