Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / Python

io.BytesIO

BytesIO guarda dados binários em memória com o cursor inicialmente a zero.

Versão: Python 3.14; repository image, production runtime not attested

Sintaxe

io.BytesIO(initial_bytes=b'')

BytesIO guarda dados binários em memória com o cursor inicialmente a zero.

Escrever b'XY' a partir da posição 1 substitui dois bytes de b'abcd'. getvalue() devolve todo o conteúdo b'aXYd' e tell() dá 3. A vista de getbuffer() permite alterar os bytes diretamente.

Enquanto existir, redimensionar ou fechar o fluxo lança 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()

Exemplos

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

Enquanto existir, redimensionar ou fechar o fluxo lança BufferError.

Fontes