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?
To find the current working directory in Python, use os. getcwd() , and to change the current working directory, use os. chdir(path) .
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.
You can change working directory after opening Spyder by typing inside IPython console cd path/to/working/dir .
To do this automatically, put this at the beginning of your script:
from os import chdir, getcwd wd=getcwd() chdir(wd)
In the interim, you can use os.chdir
import os os.chdir('C:\Users\me\Documents')
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