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)
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)
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
.