import IPython.nbformat as nbf
Let's create the new notebook object first:
nb = nbf.v4.new_notebook()
For this example, we populate it with a simple text cell and one with code. Empty notebooks are OK too, this is just for illustration purposes:
text = "This is an auto-generated notebook."
code = "1+2"
nb['cells'] = [nbf.v4.new_markdown_cell(text),
nbf.v4.new_code_cell(code) ]
Next, we write it to a file on disk that we can then open as a new notebook.
Note: This should be as easy as: nbf.write(nb, fname)
, but the current api is a little more verbose and needs a real file-like
object. We're fixing that.
filename = 'test.ipynb'
with open(filename, 'w') as f:
nbf.write(nb, f)
This notebook can be run at the command line with:
ipython -c '%run test.ipynb'
Or you can open it as a live notebook.