Get script directory or file name

Solution

To obtain the filename of the script in the file system, use the following Python code:

__file__

You can check the output by creating a Python script (a file with a .py extension) with the following content:

print(__file__)

and check what it outputs.

Note: The variable __file__ does not exist when you are in REPL (Read-Eval-Print Loop). This makes sense, as there is no script file.

Getting the directory of the script

To obtain the directory of this file, you can use the following code:

import os
	
print(os.path.dirname(__file__))

Bonus: normalizing into canonical version

Often your path might contain some non-normalized path, such as symbolic links. You can normalize the path using the following code:

import os

print(os.path.dirname(os.path.realpath(__file__)))

This is very useful if you call your script with something like python ../scripts/halting-problem.py. In that case, you might get an output such as /home/aturing/Videos/../scripts. By using realpath as shown above, you will get the canonical (or normalized) path, such as /home/aturing/scripts.

© 2023 hack nota