Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find path to current .py file in Spyder (Anaconda)?

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?

like image 959
LucSpan Avatar asked Nov 18 '22 13:11

LucSpan


1 Answers

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.

like image 161
lwileczek Avatar answered Dec 26 '22 20:12

lwileczek