jupyter / nbformat

Reference implementation of the Jupyter Notebook format
http://nbformat.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
264 stars 152 forks source link

Appending cell to the existed notebook #176

Open zkid18 opened 4 years ago

zkid18 commented 4 years ago

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)
zkid18 commented 4 years ago

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

vidartf commented 4 years ago

https://nbformat.readthedocs.io/en/latest/api.html#nbformat.read

zkid18 commented 4 years ago

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')
zkid18 commented 4 years ago

Decided to leave the issue open before anyone verify the code above.