python: get directory two levels up python: get directory two levels up python python

python: get directory two levels up


You can use pathlib. Unfortunately this is only available in the stdlib for Python 3.4. If you have an older version you'll have to install a copy from PyPI here. This should be easy to do using pip.

from pathlib import Pathp = Path(__file__).parents[1]print(p)# /absolute/path/to/two/levels/up

This uses the parents sequence which provides access to the parent directories and chooses the 2nd one up.

Note that p in this case will be some form of Path object, with their own methods. If you need the paths as string then you can call str on them.


Very easy:

Here is what you want:

import os.path as pathtwo_up =  path.abspath(path.join(__file__ ,"../.."))


I was going to add this just to be silly, but also because it shows newcomers the potential usefulness of aliasing functions and/or imports.

Having written it, I think this code is more readable (i.e. lower time to grasp intention) than the other answers to date, and readability is (usually) king.

from os.path import dirname as uptwo_up = up(up(__file__))

Note: you only want to do this kind of thing if your module is very small, or contextually cohesive.