Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

`io.StringIO.read`: reading text from memory

Read from the current position in a `StringIO` text stream, and distinguish that operation from retrieving the entire buffer with `getvalue()`.

Version: Python 3.12

Syntax

stream.read(size=-1, /) -> str  # Method signature; stream is an io.StringIO instance

io.StringIO.read is an instance method of the StringIO class in the io module. It reads from the current position in an in-memory text buffer and returns a str, not bytes. A new stream starts at the beginning of the buffer, even if you supply initial text.

Pass size positionally: stream.read(2) returns at most two characters and advances by the number of characters read. Omit size, pass a negative size, or pass None to read through the end of the stream. At the end, another read returns ''; read(0) also returns '' without moving the position, so it is not an end-of-stream test. Call seek(0) to read from the beginning again.

write(s) writes text at the current position, advances that position, and returns the number of characters written. It can overwrite existing text rather than append. getvalue() returns the entire buffered text without moving the position, so there is no need to call seek(0) first. Retrieve the result inside the with block: leaving it closes the stream and discards the buffer, and reading after closure raises ValueError.

Examples

import io

with io.StringIO('abcde') as source, io.StringIO() as target:
    first = source.read(2)
    rest = source.read()
    print(repr(first))
    print(repr(rest))
    print(repr(source.read(1)))

    source.seek(0)
    print(repr(source.read(2)))

    target.write(first)
    target.write('|')
    target.write(rest)
    result = target.getvalue()

print(repr(result))

Result

'ab'
'cde'
''
'ab'
'ab|cde'

`repr()` makes the empty result visible as `''`. After `seek(0)`, the input yields `'ab'` again, while `getvalue()` retrieves `'ab|cde'` from the output stream without rewinding it.

Related lessons

  • Python · Lesson 32 · Intermediate · Version: 3

Sources