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').

3
  • 1
    path.split('dir2')[0] ? Commented Aug 17, 2020 at 13:45
  • @venky__ This will not output what he wants. Commented Aug 17, 2020 at 13:47
  • @venky__ thank you for your answer, I am looking for a builtin function like os.path.findparent, I forgot to mention it. Commented Aug 17, 2020 at 13:47

4 Answers 4

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 
Sign up to request clarification or add additional context in comments.

4 Comments

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 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.
Ahla :) And I understood that but because this is a small function there isn't really a need to declare types
@Tomergt45 This is my writing style (';
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.

2 Comments

.parent would just return the path to the parent directory, not to dir2, isn't it?
Right, I missed that requirement initially.
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.

Comments

0

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

import os
os.path.abspath("dir1/dir2")

1 Comment

My working directory is dir3 so abspath('dir1/dir2') is not the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.