tags:

views:

380

answers:

3

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'))

but i want to get the parent dir location:

aParent
   |--a
   |  |---b.py
   |      |---templates
   |              |--------blog1
   |                         |-------page.html
   |--templates
          |--------blog1
                     |-------page.html

and how to get the aParent location

thanks

updated:

this is right:

dirname=os.path.dirname
path = os.path.join(dirname(dirname(__file__)), os.path.join('templates', 'blog1/page.html'))

or

path = os.path.abspath(os.path.join(os.path.dirname(__file__),".."))
+1  A: 

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))).

Marcelo Cantos
he seems to know about `dirname`
SilentGhost
I know the OP knows about `dirname`. It isn't obvious to everyone that applying dirname to a directory yields the parent directory.
Marcelo Cantos
hi Marcelo,look the updated
zjm1126
+2  A: 

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__)),"..",".."))
S.Mark
this is right...
zjm1126
+1  A: 
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'))
Felix Kling
o ,i know ,you are right ,and i want to get the a's parent folder. how to get it
zjm1126
@zjm1126: See Marcelo Cantos' answer. Apply `dirname()` twice. Everything you need now should be on this site.
Felix Kling