def robust_file_write(directory, filename, data):
 tempname = None
 dirfd = None
 try:
  dirfd = os.open(directory, os.O_DIRECTORY)
  with tempfile.NamedTemporaryFile(prefix=filename, dir=directory, delete=False) as tf:
   tempname = tf.name
   tf.write(data.encode('utf-8'))
   tf.flush()
   os.fdatasync(tf.fileno())
   tf.close()
   os.fsync(dirfd)
   os.rename(tempname, os.path.join(directory, filename))
   os.fsync(dirfd)
 except OSError:
  with excutils.save_and_reraise_exception():
   LOG.error(_LE('Failed to write persistence file: %(path)s.'), {'path': os.path.join(directory, filename)})
   if os.path.isfile(tempname):
    os.unlink(tempname)
 finally:
  if dirfd:
   os.close(dirfd)

def robust_file_write ( directory , filename , data ) : tempname = None dirfd = None try : dirfd = os . open ( directory , os . O_DIRECTORY ) with tempfile . NamedTemporaryFile ( prefix = filename , dir = directory , delete = False ) as tf : tempname = tf . name tf . write ( data . encode ( 'utf-8' ) ) tf . flush ( ) os . fdatasync ( tf . fileno ( ) ) tf . close ( ) os . fsync ( dirfd ) os . rename ( tempname , os . path . join ( directory , filename ) ) os . fsync ( dirfd ) except OSError : with excutils . save_and_reraise_exception ( ) : LOG . error ( _LE ( 'Failed to write persistence file: %(path)s.' ) , { 'path' : os . path . join ( directory , filename ) } ) if os . path . isfile ( tempname ) : os . unlink ( tempname ) finally : if dirfd : os . close ( dirfd )
robust file write .