Free cookie consent management tool by TermsFeed The StringIO class in Python | Pythontic.com

The StringIO class in Python

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 :

# 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:

Alice: How long is forever

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

# 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:

Whether

 


Copyright 2025 © pythontic.com