Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

io.StringIO

Provides an in-memory text stream for reading, writing and capturing Unicode text.

Version: Python 3.14; repository image, production runtime not attested

Syntax

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

Provides an in-memory text stream for reading, writing and capturing Unicode text.

Writing starts at the current cursor rather than automatically appending. Seek to the end when an append is required.

The optional initial str is already in the buffer but the cursor starts at zero. A write replaces characters and returns their count. getvalue() retrieves all text without moving the cursor. Bytes are rejected with TypeError. Replacing a with X gives Xbc, then appending ! gives Xbc!. For CRLF input, newline=None converts the line ending to LF and newline='' preserves it. getvalue() after close() raises ValueError.

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) consumes at most size characters from the current cursor. An omitted or negative size reads to the end, and EOF yields an empty string. write returns the number of characters written. getvalue retrieves the whole text without moving the 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"

Examples

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

Result

Xbc
Xbc!

The optional initial str is already in the buffer but the cursor starts at zero. A write replaces characters and returns their count. getvalue() retrieves all text without moving the cursor. Bytes are rejected with TypeError. Replacing a with X gives Xbc, then appending ! gives Xbc!. For CRLF input, newline=None converts the line ending to LF and newline='' preserves it. getvalue() after close() raises ValueError.

Sources