Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 973
Heisenberg Avatar asked Jul 15 '16 10:07

Heisenberg


People also ask

How do you set the working directory in Python?

To find the current working directory in Python, use os. getcwd() , and to change the current working directory, use os. chdir(path) .

How do I fix the working directory in Python?

To change the current working directory(CWD) os. chdir() method is used. This method changes the CWD to a specified path. It only takes a single argument as a new directory path.

How do I change directory in Spyder terminal?

You can change working directory after opening Spyder by typing inside IPython console cd path/to/working/dir .


2 Answers

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

from os import chdir, getcwd wd=getcwd() chdir(wd) 
like image 89
OSagnostic Avatar answered Oct 13 '22 19:10

OSagnostic


In the interim, you can use os.chdir

import os os.chdir('C:\Users\me\Documents') 
like image 39
NinComPoop Avatar answered Oct 13 '22 19:10

NinComPoop