title: write file even in case of any interruption
body: <p>How to make sure that file is written in case of any kind of interruption?
  Consider this code</p>
  
  <pre><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)
  </code></pre>
  
  <p>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!</p>