Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

os.path.abspath vs os.path.dirname

These are equal in string value, but are they truly equal? What is going on where?

import os

path_name1 = os.path.abspath(os.path.dirname(__file__))
path_name2 = os.path.dirname(os.path.abspath(__file__))

print(path_name1)
print(path_name2)
like image 422
Mwspencer Avatar asked Oct 18 '17 19:10

Mwspencer


People also ask

What is os path Dirname?

path. dirname() method in Python is used to get the directory name from the specified path.

What does os path Dirname 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 path Abspath?

abspath() is a built-in Python function that returns a normalized absolute version of the pathname, which means the abspath() function returns the pathname to a path passed as a parameter.

What is os path?

The os.path module is always the path module suitable for the operating system Python is running on, and therefore usable for local paths. However, you can also import and use the individual modules if you want to manipulate a path that is always in one of the different formats.


1 Answers

According to here, the value of __file__ is a string, which is set when module was imported by a loader. From here you can see that the value of __file__ is

The path to where the module data is stored (not set for built-in modules).

Usually, the path is already the absolute path of the module. So, the line 4 of your code can be simplified to path_name2 = os.path.dirname(__file__). Obviously, the line 3 of your code can be presented as path_name1 = os.path.abspath(path_name2) (let us ignore the order of execution for now).

The next thing is to see what does dirname do. In fact, you can view dirname as a wrapper of os.path.split, which splits a path into two parts: (head, tail). tail is the last part of the given path and head is the rest of the given path. So, the path_name2 is just the path of the directory containing the loaded file. Moreover, path_name2 is a absolute path. Hence os.path.abspath(path_name2) is just the same with path_name2. So, path_name1 is the same with path_name2.

like image 115
Xuanyu Wang Avatar answered Oct 20 '22 02:10

Xuanyu Wang