CKTIS / Python
io.StringIO: read, write, and retrieve the entire buffer
Use `read()` to consume text from the current position, `write()` to build output in pieces, and `getvalue()` to retrieve all the text without moving the position.
Version: Python 3.12
Syntax
io.StringIO(initial_value='', newline='\n')
Methods on a StringIO instance (signature notation):
read(size=-1, /) -> str
write(s, /) -> int
getvalue() -> strIn Python 3.12, io.StringIO is a text stream backed by memory, not a file on disk. You can supply initial text as input and use a separate, empty stream to collect output. The initial position is at the start of the buffer, even if it already contains text.
read() returns a str from the current position to the end and advances past the text it reads. read(n) reads at most n characters when n is nonnegative. At the end of the stream, read() returns ''. write(s) writes a str at the current position, advances the position, and returns the number of characters written. It does not always append: it can overwrite existing text. Passing bytes to write() raises TypeError.
getvalue() takes no arguments and returns the entire buffer as a str, regardless of the current position. It neither moves the position nor clears the buffer, so there is no need to call seek(0). It interprets newlines the same way read() does, according to the newline setting.
Retrieve the result before leaving the with block: closing the stream discards its buffer, and calling getvalue() afterward raises an exception. The str you already retrieved remains available.
Examples
import io
with io.StringIO("go") as src, io.StringIO() as dst:
text = src.read()
dst.write("[")
dst.write(text.upper() + "]")
position = dst.tell()
result = dst.getvalue()
assert dst.tell() == position
print(repr(dst.read()))
print(result)Result
'' [GO]
The example reads `go` and builds `[GO]` with two writes. `getvalue()` retrieves all of it without moving the position; the next `read()` returns `''` because the position is still at the end. The saved result can be printed after the stream closes.
Related lessons
- Python · Lesson 32 · Intermediate · Version: 3
Sources
- io — Core tools for working with streams: StringIO.getvalue()
- io — Core tools for working with streams: StringIO
- io — Core tools for working with streams: TextIOBase.read()
- io — Core tools for working with streams: TextIOBase.write()
- io — Core tools for working with streams: IOBase
- io — Core tools for working with streams: Overview