title: Writing to an external file before a blackout
body: <p>I have a python scoreboard program running on a raspberry pi, and I need it to recover the information on it after coming back from a blackout(quite frequent where I live). Below is the code for the saving mechanism only:</p>
  
  <pre><code>import pygame
  from pygame.locals import *
  
  if os.path.isfile('backup.txt'):
      print('Reloading details from previous game... ')
      backup = open('backup.txt', 'r')
  
      time_a = float(backup.readline().rstrip('\n'))
      team1name = backup.readline().rstrip('\n').upper()
      team2name = backup.readline().rstrip('\n').upper()
      team1score = int(backup.readline().rstrip('\n'))
      team2score = int(backup.readline().rstrip('\n'))
      currentperiod = int(backup.readline().rstrip('\n'))
      team1fouls = int(backup.readline().rstrip('\n'))
      team2fouls = int(backup.readline().rstrip('\n'))
      possesion = bool(backup.readline().rstrip('\n'))
  
  pygame.time.set_timer(USEREVENT + 1, 100)
  
  while True:  # Main loop
      clock.tick(30)
      for event in pygame.event.get():
  
          if event.type == USEREVENT + 1:  # Write to backup file
              backup = open('backup.txt', 'w')
              backup.write('{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n'.format(
                  str(time_a), team1name, team2name, str(team1score), str(team2score),
                  str(currentperiod), str(team1fouls), str(team2fouls), str(possesion)))
              pygame.time.set_timer(USEREVENT + 1, 100)
  
          if event.type == KEYDOWN:
              if event.key == K_ESCAPE:
                  backup.close()
                  os.remove('backup.txt')
                  sys.exit()
  </code></pre>
  
  <p>If I simulate a blackout by doing <code>kill -9 processID</code>, then re-run the program, nothing is wrong. But if I simulate a blackout by pulling the plug on my pi, <code>backup.txt</code> is empty.</p>
  
  <p>I have tried changing the frequency of the saves (<code>USEREVENT+1</code>).</p>
  
  <p>How can I get the program to save to <code>backup.txt</code> before an actual blackout?</p>