Set-up
I run a script on my computer, located in the directory Users/path/to/my/script.py
.
In the script, I use the path to the script, e.g.,
sub_path = 'Users/path/to/my/'
os.chdir(sub_path + 'other_script/')
As you can see, I define sub_path
in the code 'manually'.
Problem
I don't want to define the sub_path
manually, I'd rather have Python do it for me.
I'm looking for something similar to the code I use to obtain the current working directory: os.getcwd()
, but then a code to obtain the directory of the current file.
I mainly find answers similar to this one, which says,
os.path.abspath(os.path.dirname(__file__))
but in the Spyder & Anaconda set-up, this generates a NameError: name '__file__' is not defined
.
What can I do?