@contextmanager
def atomically_replaced_file(name, mode='w', buffering=(-1)):
 (ffd, tempname) = tempfile.mkstemp(dir=os.path.dirname(name), text=('b' not in mode))
 try:
  try:
   f = os.fdopen(ffd, mode, buffering)
  except:
   os.close(ffd)
   raise
  try:
   (yield f)
  finally:
   f.close()
  os.rename(tempname, name)
 finally:
  unlink(tempname)

@ contextmanager def atomically_replaced_file ( name , mode = 'w' , buffering = ( - 1 ) ) : ( ffd , tempname ) = tempfile . mkstemp ( dir = os . path . dirname ( name ) , text = ( 'b' not in mode ) ) try : try : f = os . fdopen ( ffd , mode , buffering ) except : os . close ( ffd ) raise try : ( yield f ) finally : f . close ( ) os . rename ( tempname , name ) finally : unlink ( tempname )
yield a file that will be atomically renamed name when leaving the block .