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?
You if you want to move back one folder/directory you use the ..
in your file path.
os.chdir('../other_scripts/')
will work. You may fine it helpful to view this or the wiki.
If you want to move from where you currently are you can use './new_dir/'
. If you want to automate how to find other files you may want to read here which says to use os.walk. This may be the same question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With