Programmatically Create Jupyter Notebook Cells

This small piece of code allows you to load any file (.py or other) and insert it as the next cell into your jupyter notebook:

from IPython.display import display_javascript

def make_cell(s):
    text = s.replace('\n','\\n').replace("\"", "\\\"").replace("'", "\\'")
    text2 = """var t_cell = IPython.notebook.get_selected_cell()
    t_cell.set_text('{}');
    var t_index = IPython.notebook.get_cells().indexOf(t_cell);
    IPython.notebook.to_code(t_index);
    IPython.notebook.get_cell(t_index).render();""".format(text)
    display_javascript(text2, raw=True)
    
def insert_file(filename):
    with open(filename, 'r') as content_file:
        content = content_file.read()
    make_cell(content)

So, this is how it looks: you call the function

insert_file(path_to_a_file)  

in some cell, and in the next cell it will put the code of this file:

How it works

Leave a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>