0
'DIRS': [os.path.join(
      os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'templates')],

resolves to:

'/opt/python/current/app/src/myproject/templates'

What change would I need to make to may code to get DIRS to resolve to the following?

'/opt/python/current/app/src/templates'
4
  • Can you post the original __file__ value? ... or its abspath, really. Commented Jul 8, 2020 at 1:11
  • I don't pass file into this. Commented Jul 8, 2020 at 1:20
  • You used __file__ and you could print absolute path to use as test input. That would make this a reproducible problem we can use for test. Otherwise we have to invent a path name ourselves and try it. Commented Jul 8, 2020 at 1:25
  • See my answer for an example. I guessed instead of verifying because I don't have sample input. Commented Jul 8, 2020 at 1:26

3 Answers 3

1

Since os.path.dirname gets the directory name for a specified file (in your case __file__, you can see what this means int here) you will get the parent directory of that file.

Now os.path.abspath gets the absolute path of the current working directory with the file name.

And last os.path.join works by joining two paths. For example, if you have are located in /opt/python/current/app/src/myproject/ and you want to join the templates folder to that path you do os.path.join(/opt/python/current/app/src/myproject/,templates)

so to get what you need you to do to get what you need

'DIRS' : [os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))),
'templates')
],

os.path.abspath gets the absolute normalized path of __file__ then it gets the parent directory with first os.path.dirname (innermost) and the second gets that resultant path parent directory and so on.

If by using two os.path.dirname you get /opt/python/current/app/src/myproject/templates that means you need one more os.path.dirname to achieve what you want.

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

Comments

1

pathlib can make this easier. Its like os.path but implemented as a class suitable for method chaining.

from pathlib import Path

filename = "would be nice if OP gave us the test input"
templates = Path(filename).absolute().parents[2].joinpath('templates')

templates is still a Path object. Some API's accept Path but you can also do templates = str(templates) to get the path string.

Comments

0

print(os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(file))), "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.