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.
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))
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))
To convert jupyter notebook files to html, use the linux command
jupyter nbconvert --to html "ipynb file path"
will do.
Use subprocess.run
to execute linux commands in python.
subprocess.run(["jupyter", "nbconvert", "--to", "html", "ipynb file path"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
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))