简体   繁体   中英

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 ie dir1/dir2 .

something like findparent(path, 'dir2') .

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 

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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM