Michael
Michael

Reputation: 4471

os.path.join - how to cope with absolute path

Python 3.5.2

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'

I want to join them:

STATIC_ROOT = os.path.join(PROJECT_PATH, STATIC_URL)

The result is '/static/'.

This is the documentation: https://docs.python.org/3/library/os.path.html

We can read that "If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component."

In my case BASE_DIR in the debugger is '/home/michael/PycharmProjects/photoarchive/photoarchive'.

Well, this is an absolute path. Well, it eve was acquired via abspath function.

So, there first component - BASE_DIR - is an absolute path.

Could you tell me why it is thrown away? And how to get '/home/michael/PycharmProjects/photoarchive/photoarchive/static'?

Upvotes: 1

Views: 685

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140307

"If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component." applies here: STATIC_URL is an absolute path because it starts with /, so BASE_DIR is dropped.

Drop the leading / else dirname thinks that STATIC_URL is absolute and keeps only that.

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = 'static/'

Upvotes: 3

Related Questions