title: Incorrect data occasionally written to disk
body: <p>I am working on a Django project which launches a single async thread monitoring the system resources because some requests need to change behaviour based on current state of the server. Code to setup the monitoring thread:</p>
  
  <pre><code>def monitor():
      try:
          f = open("file")
          data = eval(f.read())  # raises SyntaxError!?
          f.close()
      except FileNotFoundError:
          data = {
              "cpu": [0 for _ in range(720)],
              "ram": [0 for _ in range(720)],
              "disk_capacity": [0 for _ in range(720)],
              "disk_write": [0 for _ in range(720)],
              "disk_read": [0 for _ in range(720)],
              "network_sent": [0 for _ in range(720)],
              "network_recv": [0 for _ in range(720)],
              "uptime": 0
          }
  
      while True:
          f = open("file", "w")
          f.write(str(data))
          f.close()
          data = update_data(data)  # Returns every full hour
  
  class ServerStatusConfig(AppConfig):
      ...
  
      def ready(self):
          # Workaround for Django's process forking
          try:
              f = open("temp", "r")
              f.close()
          except FileNotFoundError:
              f = open("temp", "w")
              f.close()
              thread = threading.Thread(target=monitor)
              thread.start()
          else:
              os.remove("temp")
  
  def update_data(data):
      # Fetch cpu, ram, dskcap, dskw, dskr, netr, nets
      # cpu scheduled to calculate average until next full hour,
      # other stats are fetched immediately afterwards
      ...
      data["cpu"] = data["cpu"][1:]+[cpu]
      data["ram"] = data["ram"][1:]+[ram]
      data["disk_capacity"] = data["disk_capacity"][1:]+[dskcap]
      data["disk_write"] = data["disk_write"][1:]+[dskw]
      data["disk_read"] = data["disk_read"][1:]+[dskr]
      data["network_recv"] = data["network_recv"][1:]+[netr]
      data["network_sent"] = data["network_sent"][1:]+[nets]
  
      return data
  </code></pre>
  
  <p>Basically, reading the <code>str(data)</code> from file which is not read from nor written to by any other code raises a SyntaxError every so often. Syntax Error in the file is <strong>always</strong> caused by additional <code>]}</code> at the end of the file. That means that the data is recoverable and that this does technically fixes the problem:</p>
  
  <pre><code>except SyntaxError:
      data = eval(f.read()[:-2])
  </code></pre>
  
  <p>But what could be the cause for occasionally writing incorrect data to a file?</p>
  
  <p><strong>Edit</strong>: Updated code to display <code>data</code> dictionary contents on creation time.</p>
  
  <p><strong>Edit</strong>: Updated code to display <code>update_data</code> function.</p>