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?

fish748
  • 183
  • 2
  • 10

3 Answers3

4

Use the os module:

import os
a_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
shaktimaan
  • 11,962
  • 2
  • 29
  • 33
1

In Python 3:

from pathlib import Path

mypath = Path().absolute().parent.parent  # each '.parent' goes one level up - vary as required
print(mypath)
Ron Kalian
  • 3,280
  • 3
  • 15
  • 23
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.

anirudh
  • 4,116
  • 2
  • 20
  • 35
  • Won't this give the dir one level higher? What if Parent is 3 or 4 levels deep? – apomene May 09 '14 at 15:49
  • 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. – anirudh May 09 '14 at 15:50
  • 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. – Tony Suffolk 66 May 09 '14 at 18:21