3

Say there's a directory hierarchy like this: .../A/B/main.py.

main.py is the file being executed, and I need to get the full path of folder A, how can I do that?

1

3 Answers 3

4

Use the os module:

import os a_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 
Sign up to request clarification or add additional context in comments.

Comments

1

In Python 3:

from pathlib import Path mypath = Path().absolute().parent.parent # each '.parent' goes one level up - vary as required print(mypath) 

Comments

0

To get the path of the current directory, you can use:

import os print os.path.realpath('.') 

since . represents the current directory in the file system. So to get the path of the higher level directory, just replace . with .., which represents parent directory

import os print os.path.realpath('..') 

You can also use the os.getcwd() method to get the current working directory and then get its parent directory with the .. representation.

3 Comments

Won't this give the dir one level higher? What if Parent is 3 or 4 levels deep?
in that case, we can still use the normal unix or windows path traversing. Just use `../..'to the the path of a directory, two levels higher.
The OP doesn't ask for the current directory - he wants the parent of the parent of the current executing file - using "." or cwd wont do that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.