@contextmanager
def safe_file(path, suffix=None, cleanup=True):
 safe_path = u'{0}.{1}'.format(path, (suffix or uuid.uuid4()))
 if os.path.exists(path):
  shutil.copy(path, safe_path)
 try:
  (yield safe_path)
  if cleanup:
   shutil.move(safe_path, path)
  else:
   shutil.copy(safe_path, path)
 finally:
  if cleanup:
   safe_delete(safe_path)

@ contextmanager def safe_file ( path , suffix = None , cleanup = True ) : safe_path = u'{0}.{1}' . format ( path , ( suffix or uuid . uuid4 ( ) ) ) if os . path . exists ( path ) : shutil . copy ( path , safe_path ) try : ( yield safe_path ) if cleanup : shutil . move ( safe_path , path ) else : shutil . copy ( safe_path , path ) finally : if cleanup : safe_delete ( safe_path )
a with-context that copies a file .