Reputation: 8467
I have a directory structure as below
/home/damon/dev/python/misc/path/
/project/mycode.py
/app/templates/
I need to get the absolute path of the templates folder from mycode.py
I tried to write mycode.py
as
import os
if __name__=='__main__':
PRJ_FLDR=os.path.dirname(os.path.abspath(__file__))
print 'PRJ_FLDR=',PRJ_FLDR
apptemplates = os.path.join(PRJ_FLDR,'../app/templates')
print 'apptemplates=',apptemplates
I expected the apptemplates to be
/home/damon/dev/python/misc/path/app/templates
but I am getting
/home/damon/dev/python/misc/path/project/../app/templates
How do I get the correct path?
Upvotes: 2
Views: 3583
Reputation: 14768
Is this what you want?
import os
if __name__=='__main__':
PRJ_FLDR=os.path.dirname(os.path.abspath(__file__))
print 'PRJ_FLDR=',PRJ_FLDR
apptemplates = os.path.abspath(os.path.join(PRJ_FLDR, '../app/templates'))
print 'apptemplates=',apptemplates
Considering the comments, I made the proper edit.
Upvotes: 1
Reputation: 137534
That path is correct, try it. But if you want to remove the redundant 'project/../' section for clarity, use os.path.normpath
os.path.normpath(path)
Normalize a pathname. This collapses redundant separators and up-level references so that A//B, A/B/, A/./B and A/foo/../B all become A/B.
http://docs.python.org/2/library/os.path.html#os.path.normpath
Upvotes: 5
Reputation: 545
This works:
apptemplates = os.path.join(os.path.split(PRJ_FLDR)[0], "app/templates")
Upvotes: 0
Reputation: 8467
I tried this ,and it seems to work
parentpath=os.path.abspath(os.path.join(os.path.dirname(__file__),".."))
apptemplates=os.path.join(parentpath,'app/templates')
Upvotes: 0