The StringIO class in Python

The StringIO class in Python provides text read and write operations to an underlying buffer. When getbuffer() is called on a StringIO it returns the whole contents of the buffer as a string.

Stringio Updated 3 Nov 2025 1 min read

Overview

  • The StringIO class comes handy when text read/write operations are required on physical memory rather than on a disk file.
  • StringIO can be used in several read-write styles:
    • The StringIO can be initialized of an initial text
    • The underlying buffer can be retrieved as a string using getvalue() method.
    • The whole buffer can be retrieved using the read() method.
    • Several characters/code-points can be read and written to using the read() and write() functions – by specifying the number of bytes to be read/written.
    • Read and write operations can start from a valid location using the seek() method.

Example 1 - Read the whole buffer from a StringIO as a String

python
# Example Python program that reads a StringIO and

            # returns the whole contents as a string

            import io

# Create a StringIO object

            stringStream = io.StringIO()

# Write some text to the StringIO

            stringStream.write("Alice: How long is forever")

# Reset the stream position to the start

            stringStream.seek(0)

# Read all the contents in one go

            text = stringStream.read()

# Print the contents as a string

            print(text)

Output

Output
Alice: How long is forever

Example 2: Read a specified number of characters from a StringIO

python
# Example Python program that reads a specified number of

            # characters/code-points from a StringIO

            import io

# Create a stream of strings

            strStream = io.StringIO()

            strStream.write("Whether you can make words mean so many different things.")

# Read specified number of characters from the StringIO

            # i.e.,code points

            charCount = 7

            strStream.seek(0)

            chars = strStream.read(charCount)

            print(chars)

Output

Output
Whether