Tomergt45
Tomergt45

Reputation: 679

How get path of specific parent directory in python

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

Upvotes: 0

Views: 830

Answers (4)

Christian
Christian

Reputation: 1431

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

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

Upvotes: 0

phipsgabler
phipsgabler

Reputation: 20970

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.

Upvotes: 1

Dustin
Dustin

Reputation: 493

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.

Upvotes: 0

vmemmap
vmemmap

Reputation: 541

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 

Upvotes: 1

Related Questions