nbformat
nbformat copied to clipboard
Appending cell to the existed notebook
The nbf.write()
seems working pretty good with new notebook generation.
import nbformat as nbf
nb = nbf.v4.new_notebook()
text = """\
# Manual EDA with automatic notebook genration"""
code = """\
%pylab inline
hist(normal(size=2000), bins=50);"""
nb['cells'] = [nbf.v4.new_markdown_cell(text),
nbf.v4.new_code_cell(code)
]
with open('test.ipynb', 'a') as f:
nbf.write(nb, f)
But I couldn't find the same smooth method in nbformat
to append cells to existed notebook.
Is there a simpler way to that?
import json
with open('eda.ipynb', 'r') as f:
json_obj = json.load(f)
# concat cells
json_obj['cells'] = json_obj['cells'] + nb['cells']
with open('test.ipynb', 'w') as f:
json.dump(json_obj, f)
I might have missed something in official documentation, but I couldn't find a way to load the existed notebook. There is only an option of creating a new notebook
https://nbformat.readthedocs.io/en/latest/api.html#nbformat.read
Thanks, that is pretty much what I was looking for.
For everyone who came across the same request I leave the updated code
nb = nbf.read('eda_new.ipynb', as_version=4)
text = """\
# Manual EDA with automatic notebook genration"""
code = """\
%pylab inline
hist(normal(size=2000), bins=50);"""
cells = [nbf.v4.new_markdown_cell(text), nbf.v4.new_code_cell(code)]
nb['cells'].extend(cells)
nbf.write(nb, 'eda_new.ipynb')
Decided to leave the issue open before anyone verify the code above.