CKTIS / Python
io.StringIO
StringIO guarda texto Unicode em memória e aceita str na escrita.
Versão: Python 3.14; repository image, production runtime not attested
Sintaxe
io.StringIO(initial_value='', newline='\n')StringIO guarda texto Unicode em memória e aceita str na escrita.
Nos dados terminados em CRLF, newline=None normaliza o fim de linha para LF e newline='' preserva-o. Chamar getvalue() depois de close() lança ValueError. Mesmo com o texto inicial 'abc', o cursor começa em zero e escrever 'X' produz 'Xbc'. Após seek(0, 2), escrever '!' acrescenta o caráter no fim. getvalue() devolve todo o texto sem mover o cursor.
Escrever bytes lança 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) consome até size carateres a partir do cursor e avança-o. Sem tamanho ou com tamanho negativo lê até ao fim, onde devolve a cadeia vazia. write devolve o número de carateres escritos e getvalue todo o texto sem deslocar o 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"
Exemplos
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!
Escrever bytes lança TypeError.