Getting the file name of the current notebook

2,082 views
Skip to first unread message

DG

unread,
Jul 20, 2016, 12:31:22 AM7/20/16
to Project Jupyter
Here is a solution I found after much searching. It really should not be that hard. I hope it helps somebody. If anybody has a simpler solution, preferably Python-only, please let us know!
Note: Python2. 

In a separate cell:

%%javascript
var kernel = IPython.notebook.kernel;
var thename = window.location.href;
var command = "notebook_url = " + "'"+thename+"'";
kernel.execute(command);

in the next cell:

import urllib2
nb_filename = urllib2.url2pathname(notebook_url).split('/')[-1]
if nb_filename.endswith('#'):
    nb_filename = nb_filename[:-1]


I have no idea why I am getting the '#' character at the end. 

Lawrence D’Oliveiro

unread,
Jul 20, 2016, 5:01:09 AM7/20/16
to Project Jupyter
On Wednesday, July 20, 2016 at 4:31:22 PM UTC+12, DG wrote:

var command = "notebook_url = " + "'"+thename+"'";

May I suggest using

var command = "notebook_url = \"" + escape(thename) + "\""

just in case?

Lawrence D’Oliveiro

unread,
Aug 3, 2016, 10:30:54 PM8/3/16
to Project Jupyter

Or, better still:

var command = "notebook_url = urllib.parse.unquote(\"" + escape(thename) + "\")"

to give you back the string you wanted in the first place.

Reply all
Reply to author
Forward
0 new messages