如何刷新Python IO流

问题描述 投票:0回答:2
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 

我如何从流中清除我的第一个输入,使第二个流的输出刚好成为新的Hello

python iostream
2个回答
0
投票

getvalue获取整个字符串,您可以通过搜索和阅读来做您想做的事情:

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

0
投票

您可以使用功能键truncate()。它不会删除流,但会调整其大小,因此,将其设置为0将会删除流中的所有字节。您还需要使用seek()更改流的位置。与truncate()相同,为其赋予0值应将位置偏移到流的开头。祝你好运!

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())
© www.soinside.com 2019 - 2024. All rights reserved.