Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between os.path.dirname(os.path.abspath(__file__)) and os.path.dirname(__file__)

I am a beginner working on Django Project. Settings.py file of a Django project contains these 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 as I think both are pointing to the same directory. Also it would be great help if you could provide some links os.path functions.

like image 407
Rishabh Agrahari Avatar asked Jul 16 '16 15:07

Rishabh Agrahari


People also ask

What does os path Abspath (__ file __) do?

path. abspath() returns a normalized absolutized version of the pathname path which may sound fancy but it simply means that this method returns the pathname to the path passed as a parameter to this function.

What is os path dirname (__ file __)?

The os. path. dirname() is a built-in Python function that returns the directory name of the pathname path. This is the first element of the pair returned by passing a path to the function split().

What is path Abspath?

abspath (path) Return a normalized absolutized version of the pathname path. On most platforms, this is equivalent to calling the function normpath() as follows: normpath(join(os.getcwd(), path)) . Changed in version 3.6: Accepts a path-like object.

What's __ FILE __ in Python?

The __file__ variable: __file__ is a variable that contains the path to the module that is currently being imported. Python creates a __file__ variable for itself when it is about to import a module.


1 Answers

BASE_DIR is pointing to the parent directory of PROJECT_ROOT. You can re-write the two definitions as:

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 a path.

In the above, the __file__ name points to the filename of the current module, see the Python datamodel:

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file.

However, it can be a relative path, so the os.path.abspath() function is used to turn that into an absolute path before removing just the filename and storing the full path to the directory the module lives in in PROJECT_ROOT.

like image 65
Martijn Pieters Avatar answered Sep 28 '22 04:09

Martijn Pieters