Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the path of current Ipython notebook?

As simple as it sounds, how do I get the save path (location of the .ipynb file) from a cell within the notebook?

like image 503
Pedro M Duarte Avatar asked Mar 23 '15 03:03

Pedro M Duarte


People also ask

How do I find the location of my Jupyter Notebook?

Check to see if you have a notebook configuration file, jupyter_notebook_config.py . The default location for this file is your Jupyter folder located in your home directory: Windows: C:\Users\USERNAME\. jupyter\jupyter_notebook_config.py.

How do I get the current directory in Ipython?

You can use os. getcwd (current working directory) or in the native os command pwd .


2 Answers

Turns out one can use some javascript magic to get the notebook path from some attributes in the HTML body of the notebook page:

%%javascript 
var kernel = IPython.notebook.kernel; 
var proj = window.document.body.getAttribute('data-project'); 
var path = window.document.body.getAttribute('data-notebook-path'); 
var command = "proj = " + "'"+proj+"'";
kernel.execute(command);
var command = "path = " + "'"+path+"'" kernel.execute(command)

After executing the above in a cell one can get the path by doing

import os 
os.path.join( proj, path) 
like image 100
Pedro M Duarte Avatar answered Oct 19 '22 11:10

Pedro M Duarte


With Jupyter you can get the relative path of the notebook in the URL with:

%%javascript 
var kernel = Jupyter.notebook.kernel; 
var command = ["notebookPath = ",
               "'", window.document.body.dataset.notebookPath, "'" ].join('')
//alert(command)
kernel.execute(command)
var command = ["notebookName = ",
               "'", window.document.body.dataset.notebookName, "'" ].join('')
//alert(command)
kernel.execute(command)

Then you can check the python variables notebookName and notebookPath

I am not sure of the result in case of url prefix , and how to handle the case when you have already changed current directory in the notebook

like image 1
lib Avatar answered Oct 19 '22 12:10

lib