@contextmanager
def atomic_write(filepath, binary=False, fsync=False):
 tmppath = (filepath + '~')
 while os.path.isfile(tmppath):
  tmppath += '~'
 try:
  with open(tmppath, ('wb' if binary else 'w')) as file:
   (yield file)
   if fsync:
    file.flush()
    os.fsync(file.fileno())
  replace(tmppath, filepath)
 finally:
  try:
   os.remove(tmppath)
  except (IOError, OSError):
   pass

@ contextmanager def atomic_write ( filepath , binary = False , fsync = False ) : tmppath = ( filepath + '~' ) while os . path . isfile ( tmppath ) : tmppath += '~' try : with open ( tmppath , ( 'wb' if binary else 'w' ) ) as file : ( yield file ) if fsync : file . flush ( ) os . fsync ( file . fileno ( ) ) replace ( tmppath , filepath ) finally : try : os . remove ( tmppath ) except ( IOError , OSError ) : pass
writeable file object that atomically updates a file .