CKTIS / Python
io.StringIO
StringIO conserva testo Unicode in memoria e accetta str in scrittura.
Versione: Python 3.14; repository image, production runtime not attested
Sintassi
io.StringIO(initial_value='', newline='\n')StringIO conserva testo Unicode in memoria e accetta str in scrittura.
Nei dati terminati da CRLF, newline=None normalizza il fine riga in LF e newline='' lo conserva. Chiamare getvalue() dopo close() solleva ValueError. Anche con il testo iniziale 'abc', il cursore parte da zero e scrivere 'X' produce 'Xbc'. Dopo seek(0, 2), scrivere '!' aggiunge il carattere in coda. getvalue() restituisce tutto il testo senza spostare il cursore.
Scrivere bytes solleva 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) legge al massimo size caratteri dal cursore e lo avanza. Con dimensione omessa o negativa legge fino alla fine, dove restituisce la stringa vuota. write restituisce il numero di caratteri scritti e getvalue tutto il testo senza spostamento.
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"
Esempi
import io
with io.StringIO("abc") as stream:
stream.write("X")
print(stream.getvalue())
stream.seek(0, 2)
stream.write("!")
print(stream.getvalue())
Risultato
Xbc Xbc!
Scrivere bytes solleva TypeError.