elbajo elbajo - 1 year ago 92
Python Question

Python 2.7 : Write to file instantly

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'"


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

Answer Source

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

Details on using that parameter for open() here.

So you would change your open call to -

outputFile = open("./outputFile.txt", "a", 0)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download