You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

file_utils.py 1.1KB

123456789101112131415161718192021222324252627282930
  1. from pathlib import Path
  2. def search_file_upwards(
  3. base_dir_path: Path,
  4. target_file_name: str,
  5. max_search_parent_depth: int,
  6. ) -> Path:
  7. """
  8. Find a target file in the current directory or its parent directories up to a specified depth.
  9. :param base_dir_path: Starting directory path to search from.
  10. :param target_file_name: Name of the file to search for.
  11. :param max_search_parent_depth: Maximum number of parent directories to search upwards.
  12. :return: Path of the file if found, otherwise None.
  13. """
  14. current_path = base_dir_path.resolve()
  15. for _ in range(max_search_parent_depth):
  16. candidate_path = current_path / target_file_name
  17. if candidate_path.is_file():
  18. return candidate_path
  19. parent_path = current_path.parent
  20. if parent_path == current_path: # reached the root directory
  21. break
  22. else:
  23. current_path = parent_path
  24. raise ValueError(
  25. f"File '{target_file_name}' not found in the directory '{base_dir_path.resolve()}' or its parent directories"
  26. f" in depth of {max_search_parent_depth}."
  27. )