The StringIO class defined in the io module allows us to use strings with a file-like API. This means that we can use and manipulate strings as if they were files using methods like read(), write() and other file methods.

We first need to import the stringIO class before using it.

importing StringIO class

from io import StringIO

print(StringIO)

Basic Usage

The StringIO constructor has the following syntax:

StringIO(initial_value = '', newline = '\n')

initial_value is an optional parameter which specifies the initial text that will be held by the created StringIO object, it defaults to an empty string, ''. The newline parameter specifies the character used for new lines, it defaults to '\n'

Consider the following example:

from io import StringIO

#create a StringIO with initial data
string_file = StringIO('Hello, World!\nWelcome to StringIO')
print(string_file.read())

#close
string_file.close()

In the above example we instantiated a StringIO object with initial text. We then used the read() method to read its contents.

Just like in files, the close() method closes the io stream and release any associated resources. Calling this method each time, may sometimes be inconvenient. To automate this process we can use the StringIO object as  a context manager i.e using the with statement. This way, the previous example would look as follows:

from io import StringIO

with  StringIO('Hello, World!\nWelcome to StringIO') as string_file :
    print(string_file.read())

#object is automatically closed

Writing to StringIO objects

Just like in files, we can use the write() method to write data to the file.

Consider the following example:

from io import StringIO


with StringIO() as string_file:
    #write
    string_file.write("A penny for a spool of thread,\n")
    string_file.write("A penny for a needle,\n")
    string_file.write("That's the way the money goes,\n")
    string_file.write("Pop! Goes the weasel!")

    #get written data
    print(string_file.getvalue())

In the above example, we instantiated an empty StringIO object then used the write() method to add text to it.

Note that we used the getvalue() method instead of read() or other read methods such as readline() and readlines(). Using any of the later methods in the above case would yield an empty string, this is because after performing the write() operations, the "cursor" moves to the end of the file.

example with read()

from io import StringIO

with StringIO() as string_file:
    #write
    string_file.write("A penny for a spool of thread,\n")
    string_file.write("A penny for a needle,\n")
    string_file.write("That's the way the money goes,\n")
    string_file.write("Pop! Goes the weasel!")

    print(string_file.read()) #returns an empty string

We can use the seek() method with 0 as the argument to rewind the cursor to the start of the file, as shown in the following example:

from io import StringIO

with StringIO() as string_file:
    #write
    string_file.write("A penny for a spool of thread,\n")
    string_file.write("A penny for a needle,\n")
    string_file.write("That's the way the money goes,\n")
    string_file.write("Pop! Goes the weasel!")

    string_file.seek(0) #rewind the cursor to the start of the file
    print(string_file.read()) #reads everything

As you can see in the above example, after postioning the cursor at the start of the string file, read methods such as read() and readline() can read all text stored in the StringIO objcects.

In the above case, the getvalue() method is more convenient because it does not require the cursor to be re-positioned after performing various operations.

StringIO methods CheatSheet

close() Close the StringIO object. After closing, the object cannot be read from or written to.
getvalue() Get all the text stored in the StringIO object without re-postioning the cursor.
read(size = -1) Read data of the specified bytes size starting from where the cursor is. If not given, read until the end.
readline(size = -1) Read from the current line. If size is not given, read until the end of line character is encountered.
readlines(hint = -1) Return a list of lines separated by the end of line character. If hint is not given read to the end
seek(pos) Position the cursor at the given position.
tell() Check the current position of the cursor.
write(s) Write string s to the StringIO stream..