Jupyter Notebook Format
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
- breaking nbformat 5.0.0 dropped support for Python 2.x. It now requires Python 3.5+ (currently >= 3.8). If you are on an older Python 3 version, check the specific `nbformat` 5.x patch release for minimum Python requirements.
- deprecated The `nbformat.current` module is deprecated. It was intended for backward compatibility but can lead to confusion regarding notebook versions.
- gotcha The `validate()` function in nbformat 5.5.0 and later no longer attempts to fix notebook errors during validation. It will now raise a `ValidationError` for invalid notebooks rather than silently modifying them.
- gotcha When reading or writing notebooks, `nbformat.NO_CONVERT` can be passed to the `as_version` or `version` parameters to prevent any version conversion. If you omit `version` during writing, the notebook's own version will be used without conversion.
Install
-
pip install nbformat
Imports
- nbformat
import nbformat
- new_notebook
from nbformat.v4 import new_notebook
Quickstart
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.")