Skip to content

Instantly share code, notes, and snippets.

Created June 23, 2015 01:04
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 16 You must be signed in to fork a gist
  • 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
python 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, 'r', encoding='utf-8') as f:
nb =, as_version=4)
if merged is None:
merged = nb
# TODO: add an optional marker between joined notebooks
# like an horizontal rule, for example, or some other arbitrary
# (user specified) markdown cell)
if not hasattr(merged.metadata, 'name'): = '' += "_merged"
if __name__ == '__main__':
notebooks = sys.argv[1:]
if not notebooks:
print(__doc__, file=sys.stderr)
Copy link

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...

Copy link

fperez commented Feb 22, 2016

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

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.

Copy link

ruxi commented Nov 10, 2016

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

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..

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