'StringIO current stream position after object creation seems to be wrong?
I am struggling with the current stream position of StringIO objects. I create a StringIO object with initial content. Then when adding strings with write()
the content gets overwritten.
f = io.StringIO("some initial text data")
f.write(' and some strings and other stuff')
print(f.getvalue())
yields to
and some strings and other stuff
Checking the current stream position after object creation:
f = io.StringIO("some initial text data")
f.tell()
gives
0
That's pretty confusing. I expected the stream position at the end of 'some initial text data'.
I can calculate the length of the initial string and then set the position manually with f.seek(initial_string_length)
But this seems cumbersome.
Are there any other ideas?
And is this the intended behaviour of StringIO objects?
Solution 1:[1]
From the docs:
The stream is positioned at the start of the buffer
f.seek(0, 2)
did the trick. Or better f.seek(0, SEEK_END)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | rabbit_from_the_hat |