StringIO initial value not included in getvalue after write

Hey everyone!

Question

Recently I started to use StringIO and faced with strange behavior of it.
In docs it says that

The initial value of the buffer can be set by providing initial_value

When I try

import io

output = io.StringIO('Hello\n')
# if get output.getvalue() here it will rerun "Hello\n"
output.write('World!\n')
print(output.getvalue())

I get output with just “World!\n”

But if I rewrite it as

import io

output = io.StringIO()
output.write('Hello\n')
output.write('World!\n')
print(output.getvalue())

I get expected output with “Hello\nWorld!\n”

So, my question is if this behavior is correct and I need to get accustomed with it?

Specs

Python version is 3.11.0
OS: Win 11, 22H2
CPU: AMD Ryzen 5 2600

When you construct a StringIO with an initial value, it’s most often because you want to read from it, not append to it. Thus the default read/write position is the very beginning of the string. In order to append, all you have to do is move that to the end (which would prevent you from reading that data, presumably not a problem here). Try this:

import io

output = io.StringIO('Hello\n')
output.seek(0, 2)
output.write('World!\n')
print(output.getvalue())
2 Likes

Thank you!