Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Write, read, and retrieve text with io.StringIO

Use `write()` to build text in memory one piece at a time, `read()` to consume text from the current position, and `getvalue()` to retrieve the whole buffer without rewinding.

Version: Python 3.12

Syntax

Python 3.12 — method signatures for a stream created with io.StringIO(...):
stream.write(s, /) -> int
stream.read(size=-1, /) -> str
stream.getvalue() -> str

io.StringIO is a text stream backed by memory, not a disk file. A stream created with io.StringIO(text) starts at the beginning, so writing immediately can overwrite the initial text. To append instead, first call stream.seek(0, io.SEEK_END).

stream.write(s) writes a str at the current position, advances that position, and returns a character count, not a byte count or the text. Passing bytes raises TypeError; use io.BytesIO for in-memory binary data. write() does not add a line ending. The default newline='\n' does not translate line endings on writes. In a signature, / marks the parameters before it as positional-only.

stream.read(n) returns up to n characters as a str from the current position and advances past what it reads. read() or a call with None or a negative size reads to the end; at the end, read() returns ''. Use stream.seek(0) to read from the beginning.

stream.getvalue() returns the whole buffer as a str without changing the position. Retrieve the result before calling close() or leaving the with block: closing discards the buffer and prevents further use of these methods, but a string you already retrieved remains usable.

Examples

import io

with io.StringIO("red blue") as source, io.StringIO() as target:
    first = target.write(source.read(3).upper())
    second = target.write(source.read().upper())
    result = target.getvalue()
    print(first, second)
    print(repr(target.read()))

print(result)

Result

3 5
''
RED BLUE

The reads consume `red` and then ` blue`. Each `.upper()` call converts its piece to uppercase before `write()` stores it. The two `write()` calls return the character counts `3` and `5`; the second piece includes a space. `getvalue()` retrieves all of `RED BLUE`, even though `target.read()` returns `''` because the position is still at the end.

Related lessons

  • Python · Lesson 32 · Intermediate · Version: 3

Sources