I would like to see what is the best way to determine the current script directory in Python.
I discovered that, due to the many ways of calling Python code, it is ha
Hopefully this helps:-
If you run a script/module from anywhere you'll be able to access the __file__
variable which is a module variable representing the location of the script.
On the other hand, if you're using the interpreter you don't have access to that variable, where you'll get a name NameError
and os.getcwd()
will give you the incorrect directory if you're running the file from somewhere else.
This solution should give you what you're looking for in all cases:
from inspect import getsourcefile
from os.path import abspath
abspath(getsourcefile(lambda:0))
I haven't thoroughly tested it but it solved my problem.