this code is get the templates/blog1/page.html in b.py:
path = os.path.join(os.path.dirname(__file__), os.path.join(\'templates\', \'blog1/page.html\'))
Here is another relatively simple solution that:
dirname()
(which does not work as expected on one level arguments like "file.txt" or relative parents like "..")abspath()
(avoiding any assumptions about the current working directory) but instead preserves the relative character of pathsit just uses normpath
and join
:
def parent(p):
return os.path.normpath(os.path.join(p, os.path.pardir))
# Example:
for p in ['foo', 'foo/bar/baz', 'with/trailing/slash/',
'dir/file.txt', '../up/', '/abs/path']:
print parent(p)
Result:
.
foo/bar
with/trailing
dir
..
/abs
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.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)))
.
May be join two ..
folder, to get parent of the parent folder?
path = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)),"..",".."))