[IPython-dev] sample code using ipython api to get a notebook and edit it
Robert Alexander
roalexan at microsoft.com
Mon Nov 17 09:26:44 EST 2014
Thanks. Based on your feedback, I wrote some sample code:
from IPython.nbformat import current as nbf
# Create new notebook with one cell
nb = nbf.new_notebook()
with open('test.ipynb', 'w') as f:
cells = [ nbf.new_code_cell("cell 1 content") ]
nb['worksheets'].append(nbf.new_worksheet(cells=cells))
nbf.write(nb, f, 'ipynb')
f.close()
# Read the notebook and write a new cell to it
with open('test.ipynb', 'r+') as f2:
nb = nbf.read(f2, 'ipynb')
cells = nb.worksheets[0].cells
cells.append(nbf.new_code_cell("cell 2 content"))
nb.worksheets[0].cells = cells
nbf.write(nb, f2, 'ipynb')
f2.close()
This will correctly create a new notebook with a single sample cell; however, reading the notebook and appending the new cell to the existing worksheet is not quite right. The resulting file has a second worksheet with the two new cells appended to the original worksheet. Is there a better way to do what I'm trying to do?
________________________________
From: ipython-dev-bounces at scipy.org <ipython-dev-bounces at scipy.org> on behalf of Thomas Kluyver <takowl at gmail.com>
Sent: Friday, November 14, 2014 1:42 PM
To: IPython developers list
Subject: Re: [IPython-dev] sample code using ipython api to get a notebook and edit it
Hi Robert,
On 14 November 2014 10:37, Robert Alexander <roalexan at microsoft.com<mailto:roalexan at microsoft.com>> wrote:
Does somebody have some sample usage of the IPython API to get and edit a notebook, like adding/deleting cells to/from it? So far, I've been trying to use the documentation at: http://ipython.org/ipython-doc/2/api/generated/IPython.nbformat.v3.nbbase.html, but I'm having a hard time getting it to work.
You can load a notebook with the read function. Then its cells are accessible as a list, either at nb.worksheets[0].cells (nbformat 3), or at nb.cells (nbformat 4 in master). You can modify it just like any Python list. Then save it back to disk with write().
There are some changes to this API in master. We're deprecating nbformat.current: now you will use read and write from the top level of nbformat, and new_notebook, new_cell etc. from the version specific subpackages, like IPython.nbformat.v4.
Best wishes,
Thomas
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/ipython-dev/attachments/20141117/4eef5e17/attachment.html>
More information about the IPython-dev
mailing list