Jupyter Notebook Format

5.10.4 · active · verified Sat Mar 28

nbformat is the reference implementation of the Jupyter Notebook format, providing Python APIs for programmatically creating, reading, modifying, and validating Jupyter Notebook files (.ipynb). It is currently at version 5.10.4 and follows the Jupyter project's release cadence, with major versions aligning with significant changes to the notebook format specification.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a new Jupyter Notebook programmatically, add markdown and code cells, save it to a `.ipynb` file, and then read the content of an existing notebook. It uses the `nbformat.v4` module for creating notebook components, ensuring compatibility with the current Jupyter Notebook format specification version 4.

import nbformat
from nbformat.v4 import new_notebook, new_markdown_cell, new_code_cell
import os

# 1. Create a new notebook
nb = new_notebook()

# Add a markdown cell
nb.cells.append(new_markdown_cell("## My First Notebook (nbformat)"))

# Add a code cell
code_cell_content = "print('Hello from nbformat!')\nx = 1 + 2\nprint(f'The sum is: {x}')"
nb.cells.append(new_code_cell(code_cell_content))

# Define output path
notebook_filename = 'example_notebook.ipynb'

# 2. Write the notebook to a file
with open(notebook_filename, 'w', encoding='utf-8') as f:
    nbformat.write(nb, f)
print(f"Notebook '{notebook_filename}' created successfully.")

# 3. Read an existing notebook
read_nb = None
if os.path.exists(notebook_filename):
    with open(notebook_filename, 'r', encoding='utf-8') as f:
        # Specify as_version=4 to ensure it's read as the V4 format
        read_nb = nbformat.read(f, as_version=4)
    print(f"\nNotebook '{notebook_filename}' read successfully.")
    print(f"Notebook format version: {read_nb.nbformat}.{read_nb.nbformat_minor}")
    for i, cell in enumerate(read_nb.cells):
        print(f"\n--- Cell {i+1} ({cell.cell_type}) ---")
        print(cell.source)
else:
    print(f"Error: '{notebook_filename}' not found for reading.")

view raw JSON →