Skip to content

Instantly share code, notes, and snippets.

@aitatanit
Last active August 29, 2015 14:01
Show Gist options
  • Save aitatanit/5110992639b55e0c8465 to your computer and use it in GitHub Desktop.
Save aitatanit/5110992639b55e0c8465 to your computer and use it in GitHub Desktop.
ipython notebook merger
#!/usr/bin/env python
# JE Touma (aitatanit@gmail.com)
# 2014.05.17
import json
import sys
import os.path
import sys
"""
Basic code that combines two or more ipython notebooks into one.
Usage:
python ipybnb_merge notebook1 notebook2 notebook3 .... notebookn
Where notebook1 ... are ipython notebooks. If notebookn exists, it it gets appended
with notebook1 notebook2 ... in the order given. If notebookn does not exist it gets created
with the other notebooks appended in the order given.
"""
if len(sys.argv) == 2:
print 'You must have at least two notebooks to merge. Exiting...'
sys.exit()
# decide whether to append to an existing notebook or create a new one
if os.path.isfile(sys.argv[-1]):
# append to the file
fin = open(sys.argv[-1], 'rb')
data = json.load(fin)
fin.close()
cells = data['worksheets'][0]['cells']
else:
# create the file
cells = []
# create an empty notebook json structure
data = {'metadata':{'name':'new NB'},'nbformat':3,'nb_format_minor':0, 'worksheets':[{'cells':[],'metadata':{}}]}
# start appending
for nb in sys.argv[1:-1]:
print 'Processing ', nb
fin = open(nb, 'rb')
notebook = json.load(fin)
fin.close()
for cell in notebook['worksheets'][0]['cells']:
cells.append(cell)
# rewrite the cells data
data['worksheets'][0]['cells'] = cells
# dump to a file
with open(sys.argv[-1], 'wb') as fout:
json.dump(data, fout)
I needed a way to merge a few of my ipython notebooks together. Internet search didn't yield anything. So I put this simple script together. Please let me know of any issues.
Usage:
python ipybnb_merge notebook1 notebook2 notebook3 .... notebookn
Where notebook1 ... are ipython notebooks. If notebookn exists, it it gets appended with notebook1 notebook2 ... in the order given. If notebookn does not exist it gets created with the other notebooks appended in the order given.
@aitatanit
Copy link
Author

I found an alternate (and more elegant) way to do the same @ https://github.com/ipython/ipython-in-depth/blob/master/tools/nbmerge.py
Check it out....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment