BytesIO and StringIO

BytesIO and StringIO#

io.BytesIO and io.StringIO are in-memory file-like objects. Useful when a library expects a file-like and the operator already has the bytes or string in memory; or when building a buffer incrementally without paying string-concat quadratic costs.

BytesIO#

import io

buf = io.BytesIO()
buf.write(b"prefix")
buf.write(payload)
buf.seek(0)
send(buf)                       # any reader expecting a file-like

buf = io.BytesIO(b"some bytes")
buf.read(4)                     # b'some'

getvalue() returns the complete buffer as bytes without disturbing the cursor.

StringIO#

The text-mode sibling. The right accumulator when building long strings incrementally.

import io

sb = io.StringIO()
sb.write("HEAD ")
sb.write(path)
sb.write(" HTTP/1.1\r\n")
wire = sb.getvalue()

For one-shot "-".join(parts), join is shorter and faster. StringIO wins when the writer is a recursive walk, a callback, or anything that can’t easily materialise a list of parts up front.

References#