Skip to content

Instantly share code, notes, and snippets.

@fperez
Created June 23, 2015 01:04
Show Gist options
  • Save fperez/e2bbc0a208e82e450f69 to your computer and use it in GitHub Desktop.
Save fperez/e2bbc0a208e82e450f69 to your computer and use it in GitHub Desktop.
Merge/concatenate multiple IPython notebooks into one.
#!/usr/bin/env python
# Note, updated version of
# https://github.com/ipython/ipython-in-depth/blob/master/tools/nbmerge.py
"""
usage:
python nbmerge.py A.ipynb B.ipynb C.ipynb > merged.ipynb
"""
import io
import os
import sys
from IPython import nbformat
def merge_notebooks(filenames):
merged = None
for fname in filenames:
with io.open(fname, 'r', encoding='utf-8') as f:
nb = nbformat.read(f, as_version=4)
if merged is None:
merged = nb
else:
# TODO: add an optional marker between joined notebooks
# like an horizontal rule, for example, or some other arbitrary
# (user specified) markdown cell)
merged.cells.extend(nb.cells)
if not hasattr(merged.metadata, 'name'):
merged.metadata.name = ''
merged.metadata.name += "_merged"
print(nbformat.writes(merged))
if __name__ == '__main__':
notebooks = sys.argv[1:]
if not notebooks:
print(__doc__, file=sys.stderr)
sys.exit(1)
merge_notebooks(notebooks)
@ruxi
Copy link

ruxi commented Nov 10, 2016

@108michael Also interested in merging notebooks. Did you end up finding a solution?

@carlospgmat03
Copy link

Thanks a lot! I am having problems with Non-ASCII characters (say á).

Thanks to @aoboy in jupyter/nbconvert#253 I was able to solve the problem. His solution:

I changed the line from print (nbformat.writes(merged)) to
print (nbformat.writes(merged).encode('utf-8'))
basically encoding is what was missing..

@datafunk
Copy link

datafunk commented Jun 1, 2017

Just a note, I did not realise that this (fantastic btw - thanks!) script is for python 3.
After a bit of searching I found this SO thread and using the from __future__ import print_function solved the problem and let me run it with python 2.7.x

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