How to get the parent dir location
os.path.dirname(os.path.abspath(__file__))
Should give you the path to a
.
But if b.py
is the file that is currently executed, then you can achieve the same by just doing
os.path.abspath(os.path.join('templates', 'blog1', 'page.html'))
You can apply dirname repeatedly to climb higher: dirname(dirname(file))
. This can only go as far as the root package, however. If this is a problem, use os.path.abspath
: dirname(dirname(abspath(file)))
.
Use relative path with the pathlib
module in Python 3.4+:
from pathlib import Path
Path(__file__).parent
You can use multiple calls to parent
to go further in the path:
Path(__file__).parent.parent
As an alternative to specifying parent
twice, you can use:
Path(__file__).parents[1]
os.path.abspath
doesn't validate anything, so if we're already appending strings to __file__
there's no need to bother with dirname
or joining or any of that. Just treat __file__
as a directory and start climbing:
# climb to __file__'s parent's parent:
os.path.abspath(__file__ + "/../../")
That's far less convoluted than os.path.abspath(os.path.join(os.path.dirname(__file__),".."))
and about as manageable as dirname(dirname(__file__))
. Climbing more than two levels starts to get ridiculous.
But, since we know how many levels to climb, we could clean this up with a simple little function:
uppath = lambda _path, n: os.sep.join(_path.split(os.sep)[:-n])
# __file__ = "/aParent/templates/blog1/page.html"
>>> uppath(__file__, 1)
'/aParent/templates/blog1'
>>> uppath(__file__, 2)
'/aParent/templates'
>>> uppath(__file__, 3)
'/aParent'