-
-
Save fperez/e2bbc0a208e82e450f69 to your computer and use it in GitHub Desktop.
#!/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) |
Sorry @jamespjh, I totally missed this! Tracking it now as an nbconvert issue.
@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.
@108michael Also interested in merging notebooks. Did you end up finding a solution?
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..
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
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...