Convert multiple Jupyter notebooks together into an html file

This script can be used when you have multiple Jupyter notebook ipynb files and want to combine them into an html file and then combine them into one place.

Recursively searches for and converts ipynb files, even if the files span multiple folders.

First from the conclusion

You can convert it using the following script.

import shutil
from pathlib import Path
import subprocess

output_folder = "Folder path where the html file is saved"
notebook_folder = "The path of the folder where the ipynb file is stored"

path_to_notebook_folder = Path(notebook_folder)
path_to_output_folder = Path(output_folder)

for path_to_ipynb in path_to_notebook_folder.rglob("*.ipynb"):
    print(str(path_to_ipynb))
    proc = subprocess.run(["jupyter", "nbconvert", "--to", "html", str(path_to_ipynb)], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    print(proc.stdout.decode("utf8"))
    print(proc.stderr.decode("utf8"))
    path_to_src_html = path_to_ipynb.with_suffix(".html")
    path_to_dest_html = path_to_output_folder.joinpath(path_to_src_html.name)
    shutil.move(str(path_to_src_html), str(path_to_dest_html))

Description of the code

Recursive search for files

The rglob ("* .ipynb") of pathlib.Path recursively searches for ipynb files under the specified folder. Use glob ("* .ipynb") if you don't want to search recursively.

for path_to_ipynb in path_to_notebook_folder.rglob("*.ipynb"):
    print(str(path_to_ipynb))

Convert jupyter notebook files to html

To convert jupyter notebook files to html, use the linux command

jupyter nbconvert --to html "ipynb file path"

will do.

Run linux command in python

Use subprocess.run to execute linux commands in python.

subprocess.run(["jupyter", "nbconvert", "--to", "html", "ipynb file path"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

Move files with python

Finally, move the html file generated by shutil.move to the specified folder.

shutil.move(str(path_to_src_html), str(path_to_dest_html))

Recommended Posts

Convert multiple Jupyter notebooks together into an html file
[Automation] Convert Python code into an exe file
Convert HTML to text file
How to convert Python to an exe file
Combine multiple python files into one python file
Convert multiple jpg files to one PDF file