小编典典

Python 2.7:立即写入文件

python

我意识到,当我使用python写入文件时,它会等到Python文件的末尾执行它:

outputFile = open("./outputFile.txt","a")
outputFile.write("First")
print "Now you have 10sec to see that outputFile.txt is still the same as before"
time.sleep(10)
outputFile.write("Second")
print "Now if you look at outputFile.txt you will see 'First' and 'Second'"

我如何使python立即写入输出文件?


阅读 198

收藏
2020-12-20

共1个答案

小编典典

您可以使用flush(),也可以将文件对象设置为不缓冲。

有关在open()
此处使用该参数的详细信息。

因此,您可以将公开通话更改为-

outputFile = open("./outputFile.txt", "a", 0)
2020-12-20