SoFunction
Updated on 2024-11-19

The correct way for Python to get the directory where the script is located

1. Previous methodology

If you are trying to get the location of the current directory where the program is running, then you can use the () function of the os module.

If you are trying to get the directory location of the currently executing script, then you need to use the [0] variable of the sys module or [0] to get it. It's actually Python that looks for a list of search paths for the module, and [0] and [0] are the same thing because Python automatically adds [0] to the list.

Specifically, if you execute python getpath\ in the C:\test directory, then () will output "C:\test" and [0] will output "C:\test\getpath".

More specifically, the output of [0] will also change if you compile the Python script as an executable with the py2exe module:
If the dependency library is packaged as a zip file by default, then [0] will output "C:\test\getpath\";
If the zipfile=None parameter is specified, the dependency libraries will be packaged into an exe file, then [0] will output "C:\test\getpath\".

2. The right way

But none of the above is actually the location of the directory where the script file is located.
For example, there is another directory named sub in the C:\test directory; C:\test directory, sub_path.py in the sub directory, call sub_path.py; we execute it in C:\test. If we use [0] in sub_path.py, then we actually get the path to the directory "C:\test", because the Python VM executes from the beginning. If you want to get the path to sub_path.py, you have to do this:
((__file__))[0]

Although __file__ is the full path to the .py file, this variable sometimes returns a relative path and sometimes an absolute path, so you have to use the () function to handle it. In this example, (__file__) outputs "C:\test\sub\sub_path.py", while ((__file__))[0] outputs "C:\test\sub".

3. Illustrative examples

Anyway, for example, the difference between (), [0] ([0]) and __file__ is this:
Assuming the directory structure is:

Copy Code The code is as follows.

C:test

  [dir] getpath

    [file]
    [dir] sub

      [file] sub_path.py


Then we execute python getpath/ under C:\test, at which point the values inside sub_path.py corresponding to the various usages are actually:
() "C:\test", which takes the starting execution directory
[0] or [0] "C:\test\getpath", which takes the directory where the script being initially executed is located.
((__file__))[0] "C:\test\getpath\sub", which takes the directory where __file__ is located in the file sub_path.py