The difference between os.path.dirname (os.path.abspath (__ file__)) and os.path.dirname (__ file__)

I am starting to work on a Django project. The Django project Settings.py file contains the following two lines:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) 

I want to know the difference, because I think both point to the same directory. It would also be very helpful if you could provide some os.path link functions.

+8
python django
source share
1 answer

BASE_DIR points to the parent directory PROJECT_ROOT . You can rewrite the two definitions as follows:

 PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(PROJECT_ROOT) 

because the os.path.dirname() function simply removes the last segment of the path.

The __file__ header __file__ indicates the file name of the current module, see Python datamodel :

__file__ is the path to the file from which the module was loaded, if it was loaded from a file.

However, this can be a relative path, so the os.path.abspath() function is used to turn this into an absolute path before deleting only the file name and saving the full path to the directory where the module is located in PROJECT_ROOT .

+12
source share

All Articles