2

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?

4 Answers 4

5

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

3 Comments

this would yield home/damon/dev/python/misc/path/project/app/templates which is wrong..it should be home/damon/dev/python/misc/path/app/templates
I'd recommend joining the paths and then normalizing: os.path.abspath(os.path.join(PRJ_FLDR, '../app/templates'))
Hugh is right, you need to do the join first then the abspath, otherwise the code is wrong. (Although it happens it will be correct when the working directory is PRJ_FLDR).
0

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

Comments

0

This works:

apptemplates = os.path.join(os.path.split(PRJ_FLDR)[0], "app/templates")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.