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\'))
I tried:
import os
os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), os.pardir))
os.pardir
is a better way for ../
and more readable.
import os
print os.path.abspath(os.path.join(given_path, os.pardir))
This will return the parent path of the given_path
Use the following to jump to previous folder:
os.chdir(os.pardir)
If you need multiple jumps a good and easy solution will be to use a simple decorator in this case.
I think use this is better:
os.path.realpath(__file__).rsplit('/', X)[0]
In [1]: __file__ = "/aParent/templates/blog1/page.html"
In [2]: os.path.realpath(__file__).rsplit('/', 3)[0]
Out[3]: '/aParent'
In [4]: __file__ = "/aParent/templates/blog1/page.html"
In [5]: os.path.realpath(__file__).rsplit('/', 1)[0]
Out[6]: '/aParent/templates/blog1'
In [7]: os.path.realpath(__file__).rsplit('/', 2)[0]
Out[8]: '/aParent/templates'
In [9]: os.path.realpath(__file__).rsplit('/', 3)[0]
Out[10]: '/aParent'
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'
A simple way can be:
import os
current_dir = os.path.abspath(os.path.dirname(__file__))
parent_dir = os.path.abspath(current_dir + "/../")
print parent_dir