10

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)
Mwspencer
  • 1,142
  • 3
  • 18
  • 35

1 Answers1

4

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.

  • Okay this makes sense, however how can line 4 be simplified to path_name2 = os.path.dirname(__file__). That just seems to return a blank output of with a len of 0. Though thanks to your answer I understand why os.path.dirname(os.path.abspath)) is what it is. – Mwspencer Oct 18 '17 at 20:09
  • If you put the code into a file, say "test.py", and execute it with command "python3 test.py", you will find that the output of "os.path.dirname(__file__)" is blank. However, if you open an python interpreter, and use "import test", you will find the output is not blank. – Xuanyu Wang Oct 19 '17 at 20:38