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

CKTIS / Python

io.StringIO

StringIO guarda texto Unicode en memoria y acepta str en write().

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

Sintaxis

io.StringIO(initial_value='', newline='\n')

StringIO guarda texto Unicode en memoria y acepta str en write().

En datos terminados en CRLF, newline=None normaliza el fin de línea a LF y newline='' lo conserva. Llamar a getvalue() después de close() lanza ValueError. Incluso con el texto inicial 'abc', el cursor empieza en cero y escribir 'X' produce 'Xbc'. Después de seek(0, 2), escribir '!' añade el carácter al final. getvalue() devuelve todo el texto sin mover el cursor.

Escribir bytes lanza TypeError.

import io
s=io.StringIO('éa')
assert s.tell()==0 and s.read(1)=='é'
s.seek(0)
assert s.write('猫')==1 and s.getvalue()=='猫a'
s.seek(0,2)
s.write('!')
assert s.getvalue()=='猫a!'
try: s.write(b'x')
except TypeError: pass
else: raise AssertionError
for newline,expected in [(None,'x\n'),('','x\r\n')]:
    with io.StringIO('x\r\n',newline=newline) as text:
        assert text.read()==expected
    try: text.getvalue()
    except ValueError: pass
    else: raise AssertionError

io.StringIO.read · io.StringIO.write · io.StringIO.getvalue

read(size) consume hasta size caracteres desde el cursor y lo adelanta. Sin tamaño o con tamaño negativo lee hasta el final, donde devuelve la cadena vacía. write devuelve el número de caracteres escritos y getvalue todo el texto sin desplazar el cursor.

from io import StringIO
with StringIO("éxy") as s:
    assert s.read(1)=="é" and s.tell()==1
    assert s.write("A")==1 and s.getvalue()=="éAy" and s.tell()==2
    assert s.read(8)=="y" and s.read(1)==""
    s.seek(0)
    assert s.read()=="éAy"

Ejemplos

import io
with io.StringIO("abc") as stream:
    stream.write("X")
    print(stream.getvalue())
    stream.seek(0, 2)
    stream.write("!")
    print(stream.getvalue())

Resultado

Xbc
Xbc!

Escribir bytes lanza TypeError.

Fuentes