Base de conocimientosCentro de exámenes
ESEspañol
Elegir idioma13

CKTIS / Python

io.BytesIO

BytesIO mantiene datos binarios en memoria con el cursor inicialmente en cero.

Versión: Python 3.14; repository image, production runtime not attested

Sintaxis

io.BytesIO(initial_bytes=b'')

BytesIO mantiene datos binarios en memoria con el cursor inicialmente en cero.

Escribir b'XY' desde la posición 1 sustituye dos bytes de b'abcd'. getvalue() devuelve todo el contenido b'aXYd' y tell() da 3. La vista de getbuffer() permite modificar los bytes directamente.

Mientras exista, cambiar el tamaño o cerrar el flujo lanza BufferError.

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()

Ejemplos

import io
with io.BytesIO(b"abcd") as stream:
    stream.seek(1)
    stream.write(b"XY")
    print(stream.getvalue(), stream.tell())

Resultado

b'aXYd' 3

Mientras exista, cambiar el tamaño o cerrar el flujo lanza BufferError.

Fuentes