Python 2.7:立即写入文件 [英] Python 2.7 : Write to file instantly

查看:35
本文介绍了Python 2.7:立即写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I realized that when I write into a file using python it wait until the end of my Python file to execute it:

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 立即写入输出文件?

How am I suppose to make python write instantly to the output file?

推荐答案

您可以使用 flush() 或者您可以将文件对象设置为无缓冲.

You can use flush() or you can set the file object to be unbuffered.

使用该参数的详细信息 open() 这里.

Details on using that parameter for open() here.

所以你会改变你的公开电话 -

So you would change your open call to -

outputFile = open("./outputFile.txt", "a", 0)

这篇关于Python 2.7:立即写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆