python: get directory two levels up
Ok...I dont know where module
x is, but I know that I need to get the path to the directory two levels up.
So, is there a more elegant way to do:
import os two_up = os.path.dirname(os.path.dirname(__file__))
Solutions for both Python 2 and 3 are welcome!
from pathlib import Path p = Path(__file__).parents 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.
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.