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
  • 6,595
  • 10
  • 38
  • 44

1 Answers1

3

Flush the buffer immediately after writing it:

FH.write(mystr)
FH.flush()
Barmar
  • 669,327
  • 51
  • 454
  • 560