Instantly share code, notes, and snippets.

Embed
What would you like to do?
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)
@jamespjh

This comment has been minimized.

Copy link

jamespjh commented Jul 13, 2015

Hey Fernando. Any plan to add this as a feature to nbconvert? Would be nice to be able to specify multiple notebooks in an nbconvert command line and have it concatenate them all into chapters of a latex book...

@fperez

This comment has been minimized.

Copy link
Owner Author

fperez commented Feb 22, 2016

Sorry @jamespjh, I totally missed this! Tracking it now as an nbconvert issue.

@108michael

This comment has been minimized.

Copy link

108michael commented Aug 10, 2016

@jamespjh I have to merge about 20 notebooks; is there a way to implement a wild card to capture all folders with the same prefix?

How do I capture the and save the merged file? Later I need to send it to Latex.

@ruxi

This comment has been minimized.

Copy link

ruxi commented Nov 10, 2016

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

@carlospgmat03

This comment has been minimized.

Copy link

carlospgmat03 commented May 4, 2017

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

This comment has been minimized.

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