@contextmanager
def temp_output_dir(output_dir, temp_dir=None, backup_suffix=None):
  '''
  If we want to write several files to a given output directory, and we would
  like all to appear at nearly the same time, we can put all files in a temporary
  location (by default a subdirectory of the output directory), and then move
  them to the final desired location at the end. This does not provide perfect
  transactionality, but helps to minimize chances of files being in an
  inconsistent state following an interruption.
  '''
  try:
    if not temp_dir:
      temp_dir = join_path(output_dir, "%s.%s" % (TMP_DIR_PREFIX, new_uid()))
    make_all_dirs(temp_dir)
    yield temp_dir

    # Now copy over all files, preserving paths. Note target may contain some
    # of the same subdirectories, so we have to do this file by file.
    for path in list_files_recursive(temp_dir):
      src = join_path(temp_dir, path)
      dest = join_path(output_dir, path)
      log.debug("moving from temp dir: %s -> %s", src, dest)
      movefile(src, dest, make_parents=True, backup_suffix=backup_suffix)
  finally:
    try:
      for dir in list_dirs_recursive(temp_dir):
        os.rmdir(join_path(temp_dir, dir))
      os.rmdir(temp_dir)
    except Exception, e:
      log.warn("error cleaning up temporary directory: %s: %s", temp_dir, e)
dataset/ETHPy150Open bloomreach/zinc/zinc.py/temp_output_dir/original