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?
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?
Use the os
module:
import os
a_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
In Python 3:
from pathlib import Path
mypath = Path().absolute().parent.parent # each '.parent' goes one level up - vary as required
print(mypath)
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.