假设这样的文本
In [134]: !cat test1.md
The first test
我打开并写内容
In [156]: f1 = open("test1.md", "r+")
In [157]: f1.write("The second test")
Out[157]: 15
In [158]: !cat test1.md
The first test
test second method
如果继续执行input
In [159]: f1.write("The third test")
Out[159]: 14
In [160]: !cat test1.md
The first test
test second method
In [161]: f1.write("The fourth test")
Out[161]: 16
In [162]: !cat test1.md
The first test
test second method
f.write
有什么问题?。
答案 0 :(得分:0)
您需要先flush()
缓冲区,然后close()
文件。也可以将您的字符串附加到文件中。
f1 = open("test1.md", "a") # "a" means append to file
f1.write("The second test")
f1.flush()
f1.close()
cat
文件;
cat test1.md
The first test
test second method
您应该真的像这样做
with open("test1.md", "a") as f1:
f1.write("The second test")
f1.flush()
f1.close()