Writes to `filename` atomically.

  This means that when `filename` appears in the filesystem, it will contain
  all of `contents`. With write_string_to_file, it is possible for the file
  to appear in the filesystem with `contents` only partially written.

  Accomplished by writing to a temp file and then renaming it.

  Args:
    filename: string, pathname for a file
    contents: string, contents that need to be written to the file
    overwrite: boolean, if false it's an error for `filename` to be occupied by
      an existing file.

def atomic_write_string_to_file(filename, contents, overwrite):
  """Writes to `filename` atomically.

  This means that when `filename` appears in the filesystem, it will contain
  all of `contents`. With write_string_to_file, it is possible for the file
  to appear in the filesystem with `contents` only partially written.

  Accomplished by writing to a temp file and then renaming it.

  Args:
    filename: string, pathname for a file
    contents: string, contents that need to be written to the file
    overwrite: boolean, if false it's an error for `filename` to be occupied by
      an existing file.
  """
  temp_pathname = (tf.compat.as_bytes(filename) +
                   tf.compat.as_bytes(".tmp") +
                   tf.compat.as_bytes(uuid.uuid4().hex))
  with tf_v1.gfile.GFile(temp_pathname, mode="w") as f:
    f.write(contents)
  try:
    tf_v1.gfile.Rename(temp_pathname, filename, overwrite)
  except tf.errors.OpError:
    tf_v1.gfile.Remove(temp_pathname)
    raise