Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Appending cell to the existed notebook #176

Open
zkid18 opened this issue Apr 6, 2020 · 4 comments
Open

Appending cell to the existed notebook #176

zkid18 opened this issue Apr 6, 2020 · 4 comments

Comments

@zkid18
Copy link

zkid18 commented Apr 6, 2020

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
Copy link
Author

zkid18 commented Apr 6, 2020

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
Copy link
Contributor

vidartf commented Apr 6, 2020

@zkid18
Copy link
Author

zkid18 commented Apr 7, 2020

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 zkid18 closed this as completed Apr 7, 2020
@zkid18 zkid18 reopened this Apr 7, 2020
@zkid18
Copy link
Author

zkid18 commented Apr 7, 2020

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants