CKTIS / Python
io.BytesIO
Creates a seekable in-memory binary stream.
Version: Python 3.14; repository image, production runtime not attested
Syntax
io.BytesIO(initial_bytes=b'')Creates a seekable in-memory binary stream.
Writes begin at the current cursor and can overwrite existing bytes. The full buffer can be read independently of the current cursor position.
The optional initial bytes populate the buffer with the cursor at zero. getvalue() returns the full contents. A writable view from getbuffer() can change bytes in place. While a view exists the stream cannot be resized or closed. Seeking to one then writing b'XY' yields b'aXYd' and position 3.
import io
s=io.BytesIO(b'ab')
v=s.getbuffer()
v[0]=ord('z')
assert s.getvalue()==b'zb' and s.tell()==0
for op in (s.close, lambda: (s.seek(0,2),s.write(b'!'))):
try: op()
except BufferError: pass
else: raise AssertionError
v.release()
s.close()
Examples
import io
with io.BytesIO(b"abcd") as stream:
stream.seek(1)
stream.write(b"XY")
print(stream.getvalue(), stream.tell())
Result
b'aXYd' 3
The optional initial bytes populate the buffer with the cursor at zero. getvalue() returns the full contents. A writable view from getbuffer() can change bytes in place. While a view exists the stream cannot be resized or closed. Seeking to one then writing b'XY' yields b'aXYd' and position 3.