Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Working Directory to Notebook Directory

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?

like image 634
pjc42 Avatar asked Jan 01 '15 23:01

pjc42


People also ask

How do I change working directory in Jupyter lab?

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 .


1 Answers

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.

like image 193
Chinmay Kanchi Avatar answered Sep 22 '22 02:09

Chinmay Kanchi