Set working directory to notebook directory

In IPython nb, is it possible to programmatically set the working directory to a laptop directory?

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 not find the equivalent

 __file__ 

for ipython nb file. Is there an equivalent approach for ipynb files?

+6
source share
1 answer

iPython notebook automatically switches the directory to the same file as the .ipynb file. Do you want to change this directory and then change it later? If so, just save the source directory at the beginning 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: A special variable _dh , which is a list, so that _dh[0] contains the name of the directory in which the iPython kernel was run. I just opened this, so I'm not sure if this will be reliable for SaveAs (I cannot find a way to do this in my version of iPython). However, this does not change when I do os.chdir() , so I suspect that at least the first element of the list always contains a notebook directory.

+7
source

Source: https://habr.com/ru/post/980415/


All Articles