How can I find script's directory?
You need to call os.path.realpath
on __file__
, so that when __file__
is a filename without the path you still get the dir path:
import os
print(os.path.dirname(os.path.realpath(__file__)))
Try sys.path[0]
.
To quote from the Python docs:
As initialized upon program startup, the first item of this list,
path[0]
, is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input),path[0]
is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result ofPYTHONPATH
.
Source: https://docs.python.org/library/sys.html#sys.path
I use:
import os
import sys
def get_script_path():
return os.path.dirname(os.path.realpath(sys.argv[0]))
As aiham points out in a comment, you can define this function in a module and use it in different scripts.