In an IPython nb, is it possible to set programmatically the working directory to the directory of the notebook?
For example, the following code will work in a regular .py file.
import os
# show working dir
os.chdir(os.path.abspath('/'))
print "initial working directory:\t", os.getcwd()
# get path of script file
scriptPath = os.path.abspath(os.path.dirname(__file__))
# change working dir to dir with script file
os.chdir(scriptPath)
# show working directory
print "final working directory:\t", os.getcwd()
However, I can't find the equivalent of the
__file__
variable for a ipython nb file. Is there some equivalent approach for ipynb files?
How to change the working directory of Jupyter and Jupyter Lab on Windows environment. Open cmd (or Anaconda Prompt) and run jupyter notebook --generate-config . This writes a file to C:\Users\username\. jupyter\jupyter_notebook_config.py .
iPython notebook appears to automatically switch the directory to the same one as the .ipynb file. Do you want to change out of that directory and then change back later? If so, just store the original directory at the start of the program and use it whenever.
import os
orig_dir = os.getcwd()
os.chdir('/some/other/directory')
#do stuff
os.chdir(orig_dir)
EDIT: There appears to be a special variable _dh
, which is a list such that _dh[0]
contains the name of the directory in which the iPython kernel was started. I only just discovered this, so I'm not sure that this will be robust to a SaveAs either (I can't find a way to do this in my version of iPython). However, it doesn't change when I do os.chdir()
, so I suspect that at least the first element of the list always contains the notebook's directory.
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