I have a pathlib.Path object and want to find the absolute path to a parent folder, called "BASE". However, I do not know how much further up the device tree the "BASE" folder is. I just know the pathlib.Path will contain a folder called "BASE". Example:
import pathlib
# the script is located at:
my_file_dir = pathlib.Path(__file__).parent
# some pathlib function to find the absolute path to BASE
# input_1: /some/path/BASE/some/more/layers/script.py
# output_1: /some/path/BASE
# input_2: /usr/BASE/script.py
# output_2: /usr/BASE
In earlier python versions I would use os.path, os.path.split() and search for the string to get the directory. Now, it seems, pathlib should be used for these things. But how?
EDIT: Here is how I solved it using pathlib.
def get_base_dir(current_dir: Path, base: str) -> Path:
base_parts = current_dir.parts[:current_dir.parts.index(base)+1]
return Path(*base_parts)
Honestly, @victor__von__doom's solution is better.