Reputation: 362
import io
string_out = io.StringIO()
string_out.write("hello")
print(string_out.getvalue())
string_out.write("new Hello")
print(string_out.getvalue())
OutPut1: hello
OutPut2: hellonew Hello
How i can i flush my first input from the stream so the out put of second stream become just new Hello
Upvotes: 5
Views: 10052
Reputation: 1930
create a new StringIO
rather than truncating and seeking.When you just go through this thread , In Python 3 creating a new Stream instead of reusing a blank stream is 11%
faster and creating a new one instead of reusing a stream with 3KB
data is 5% faster.
Upvotes: 0
Reputation: 376
You can use the functon truncate()
. It doesn't delete the stream but resizing it, so giving it a value of 0 should get rid of all the bytes in the stream. You will also need to use seek()
to change the position of the stream. Same as truncate(), giving it a value of 0 should offset the position to the start of the stream. Good luck!
import io
string_out = io.StringIO()
string_out.write("hello")
print(string_out.getvalue())
string_out.seek(0)
string_out.truncate(0)
string_out.write("new Hello")
print(string_out.getvalue())
Update: What's the difference between truncate(0) and truncate()?
truncate() uses the current default position, while truncate(0) uses the start position. Because you already specified seek(0) before truncate(0), the position is swetched to the start of the sentence before truncating. The below examples should clear it up for you.
seek(10)
and truncate()
:seek(0)
and truncate()
:Upvotes: 5
Reputation: 7224
getvalue get's the entire string, you can do what your looking for by seeking and reading:
import io
string_out = io.StringIO()
string_out.write("hello")
string_out.seek(0)
print(string_out.read())
# hello
string_out.write("new Hello")
string_out.seek(0+len("hello"))
print(string_out.read())
# new Hellow
Upvotes: 0