atomically write a file (using a temporary file).

  filename: the file to be written
  filesync: flush the file to disk

def atomic_write(filename, filesync=False):
  """ atomically write a file (using a temporary file).

  filename: the file to be written
  filesync: flush the file to disk
  """

  tmpf = tempfile.NamedTemporaryFile(delete=False)
  try:
    with open(tmpf.name, 'w') as curfile:
      yield curfile
      if filesync:
        curfile.flush()
        os.fsync(curfile.fileno())
    os.rename(tmpf.name, filename)
  finally:
    try:
      os.remove(tmpf.name)
    except (IOError, OSError):
      pass