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()
    var t_index = IPython.notebook.get_cells().indexOf(t_cell);
    display_javascript(text2, raw=True)
def insert_file(filename):
    with open(filename, 'r') as content_file:
        content =

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


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>