0

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.

Lukas
  • 27
  • 6
  • You are searching for relative paths, does [this](https://stackoverflow.com/questions/54401973/pythons-pathlib-get-parents-relative-path) answer your question? – Thymen Mar 11 '21 at 19:19
  • Thanks for your reply. Not really, because the user may save and execute the script in different locations. I can only be certain about the folder BASE and that script.py will be in some subdirectory of it. e.g. `/root/BASE/some/script.py` or `/somePath/BASE/script.py` should both be found. – Lukas Mar 11 '21 at 19:37

1 Answers1

1

I think you could do this more simply using some basic string processing on the command line args:

import sys

script_path, my_file_dir = sys.argv[0], ''
try:
    my_file_dir = script_path[:script_path.index('BASE')]
except ValueError:
    print("No path found back to BASE"); exit()

sys seems like a much easier option than pathlib here.

v0rtex20k
  • 1,041
  • 10
  • 20