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.
pip install nbformatVerified import paths — ran on the pinned version, not inferred.
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.
Upgrade your Python environment to Python 3.8 or newer.
Directly import from specific version modules like `nbformat.v4` (e.g., `from nbformat.v4 import new_notebook`) for programmatic notebook creation and manipulation, and use `nbformat.read()` or `nbformat.write()` for file I/O.
Ensure your notebooks strictly conform to the expected schema *before* calling `validate()`. If you need to upgrade older notebooks, use `nbformat.convert(nb_node, to_version=4)` explicitly, or rely on `nbformat.read(..., as_version=4)` which performs conversion if needed.
Be explicit about desired notebook format versions. If you want to ensure a specific output format, always set `version=4` (or another target version) in `nbformat.write()`. Similarly, when reading, use `as_version=4` if you want the returned object to be converted to that version.
Ensure `nbformat` is installed in the correct environment by running: `pip install nbformat` or `conda install nbformat`. If using an IDE like VS Code, verify the selected Python interpreter matches the environment where `nbformat` was installed.
Upgrade `nbformat` to the latest version: `pip install --upgrade nbformat`. After upgrading, it is often necessary to restart the kernel or the entire Jupyter/VS Code session.
Use the `nbformat.validator.normalize()` function to add missing ID fields and normalize the notebook structure. For example: `import nbformat; from nbformat import validator; with open('problematic.ipynb', 'r') as f: nb_corrupted = nbformat.read(f, as_version=4); nb_fixed = validator.normalize(nb_corrupted); with open('fixed.ipynb', 'w') as f_out: nbformat.write(nb_fixed, f_out)`. Newer versions of nbformat (>=5.1.4) provide this `normalize` method.Ensure the notebook file is well-formed JSON. If the issue is due to a version mismatch, explicitly specify the `as_version` parameter when reading (`nbformat.read(fp, as_version=4)`), or ensure the notebook's internal `nbformat` and `nbformat_minor` metadata fields correctly reflect its structure. For deep corruption, manual inspection and correction of the `.ipynb` file as plain text might be necessary, or attempting to convert it with a compatible `nbconvert` version.