0

I have path = "dir1/dir2/dir3/file.py"

I need a way to get the full path to dir2 i.e. dir1/dir2.

something like findparent(path, 'dir2').

Tomergt45
  • 579
  • 1
  • 7
  • 19

4 Answers4

1

You can split the path by the target directory, take the first element from the list, and then add the target directory to the target path.

path = "dir1/dir2/dir3/file.py"

def findparent(path: str, dir_: str) -> str:
    return path.split(dir_)[0] + dir_

print(findparent(path, 'dir2'))
# dir1/dir2 
vmemmap
  • 510
  • 4
  • 20
  • I look for this exactly but without the need to define the function myself, if no one would mention a builtin function that does the same then I would mark this as the accepted answer – Tomergt45 Aug 17 '20 at 13:54
  • @Tomergt45 Sababa. Also, I added the `path: str` to point the datatype that the function needs to get. And the `-> str` points the datatype that the function will return. – vmemmap Aug 17 '20 at 13:55
  • Ahla :) And I understood that but because this is a small function there isn't really a need to declare types – Tomergt45 Aug 17 '20 at 13:57
  • @Tomergt45 This is my writing style ('; – vmemmap Aug 17 '20 at 13:57
1

If you use pathlib and the path actually exists:

path.resolve().parent

Just path.parent also works, purely syntactically, but has some caveats as mentioned in the docs.

To find one specific part of the parent hierarchy, you could iteratively call parent, or search path.parents for the name you need.

phipsgabler
  • 20,535
  • 4
  • 40
  • 60
0

Assuming your current work directory is at the same location as your dir1, you can do:

import os
os.path.abspath("dir1/dir2")
vmemmap
  • 510
  • 4
  • 20
Christian
  • 1,341
  • 1
  • 16
  • 35
0

Check this out! How to get the parent dir location

My favorite is

from pathlib import Path

Path(__file__).parent.parent.parent # ad infinitum

You can even write a loop to get to dir2, something like this..

from pathlib import Path
goal_dir = "dir2"
current_dir = Path(__file__)
for i in range(10):
    if current_dir == goal_dir:
        break
    current_dir = current_dir.parent

Note: This solution is not the best, you might want to use a while-loop instead and check if there is actually a parent. If you are at root level and there is no parent, then it doesn't exist. But, assuming it exists and you don't have a tree deeper than 10 levels, this works.

Dustin
  • 483
  • 3
  • 13