Set the working directory in Python / Spyder so that it plays

Based on R, using setwd to change a directory is great, but not against reproducibility, because others do not have the same directory structure as mine. Therefore, it is recommended that you use the relative path from the location of the script.

IDEs complicate this a bit because they install their own working directory. In Rstudio, I can easily get around this problem with Rstudio projects by setting the project directory to the script folder.

With Python and Spyder there is no solution. Spyder does not have a feature like the Rstudio project. Setting the directory to the script folder does not work during interactive analysis (since __file__ not available).

What to do to make the working directory in Python / Spyder play?

+9
source share
5 answers

To do this automatically, put this at the top of your script:

 from os import chdir, getcwd wd=getcwd() chdir(wd) 
+5
source

You can use os.chdir at the same time.

 import os os.chdir('C:\Users\me\Documents') 
+4
source

It seems like they saw this as a function in Spyder based on this GitHub ticket, but it is still awaiting implementation from mid-May:

We could add a parameter to the Run dialog to automatically set the working directory to which your script is running.

However, someone will have to implement it. We are very busy with other things at the moment, sorry.

https://github.com/spyder-ide/spyder/issues/3154

@ ccordoba12 ccordoba12 added May 14 to my wishlist

+2
source

Well, there are many things you can try! 1. Change the directory to the current directory in the toolbar. 2. Change the global directory to the current directory under Settings> Global Working Directory. Click the "Current file directory" radio button.

Hope this helps!

0
source

I tried this and it works.

 import os abspath = os.path.abspath('') ## String which contains absolute path to the script file os.chdir(abspath) ## Setting up working directory 
0
source

All Articles