Merge Jupyter Notebooks with python script

Опубликовано: 02 Июнь 2026
на канале: Arif Hasnat Mubin
59
2

import nbformat
import glob
import re

def extract_number(filename):
match = re.match(r"(\d+)", filename)
return int(match.group(1)) if match else float('inf')

notebooks = [f for f in glob.glob("*.ipynb") if f != "Merged.ipynb"]
notebooks.sort(key=extract_number)

merged = nbformat.v4.new_notebook()

for nb_file in notebooks:
try:
with open(nb_file, "r", encoding="utf-8") as f:
nb = nbformat.read(f, as_version=4)

for cell in nb.cells:
if cell.cell_type == "code":
if "outputs" not in cell:
cell["outputs"] = []
if "execution_count" not in cell:
cell["execution_count"] = None

merged.cells.append(nbformat.v4.new_markdown_cell(f"### 📘 {nb_file}"))
merged.cells.extend(nb.cells)
except Exception as e:
print(f"⚠️ Skipping {nb_file} due to error: {e}")

with open("Merged.ipynb", "w", encoding="utf-8") as f:
nbformat.write(merged, f)

print("✅ Merged into Merged.ipynb successfully!")