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
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
您可以使用功能键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())