Get script directory or file name


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


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


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

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


This is very useful if you call your script with something like python ../scripts/ 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