2

How to make sure that file is written in case of any kind of interruption? Consider this code

with open('output.txt', 'a') as FH:
    for i in range(5):
        mystr = 'some text %d\n' %i
        FH.write(mystr)
        time.sleep(2)

If this code is running and you interrupt it using Ctrl+c it still writes the output file. But if you use Ctrl+z it do not write anything in the file!

d.putto
  • 7,185
  • 11
  • 39
  • 45

1 Answers1

3

Flush the buffer immediately after writing it:

FH.write(mystr)
FH.flush()
Barmar
  • 741,623
  • 53
  • 500
  • 612