Set working directory in Python / Spyder so that it's reproducible

Heisenberg picture Heisenberg · Jul 15, 2016 · Viewed 47.6k times · Source

Coming from R, using setwd to change the directory is a big no-no against reproducibility because others do not have the same directory structure as mine. Hence, it's recommended to use relative path from the location of the script.

IDEs slightly complicate this because they set their own working directory. In Rstudio, I can easily get around this problem with Rstudio's projects, setting the project's directory to be my script folder.

With Python and Spyder, there doesn't seem to be any solution. Spyder does not have a feature like Rstudio's project. Setting the directory to the script's location does not work while doing interactive analysis (since __file__ is not available).

What to do so that the working directory in Python / Spyder is reproducible?

Answer

OSagnostic picture OSagnostic · Jul 18, 2017

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

from os import chdir, getcwd
wd=getcwd()
chdir(wd)