Convert Jupyter Notebook (.ipynb) to Python script (.py)

Jupyter Notebook · Production · Approx. 8 min read

Notebooks are great for exploration, but scripts are easier to test, deploy, and submit in coding interviews or assignments. Here are three ways to convert .ipynb files to .py – plus a tip on keeping them reproducible.

1. “Download as → Python (.py)” from the Jupyter UI

  1. Open your notebook in classic Jupyter Notebook.
  2. File → Download as → Python (.py).
  3. You’ll get a notebook.py file with your code and comments.

2. Use nbconvert from the command line

jupyter nbconvert --to python notebook.ipynb

This writes notebook.py in the same folder.

Convert all notebooks in a folder:

jupyter nbconvert --to python *.ipynb

3. Convert from inside a notebook

!jupyter nbconvert --to python notebook.ipynb

Handy when you’re working in Colab or another environment where you have shell access inside the notebook.

4. Clean up the script after converting

5. Capture the original notebook state with NoteCapsule

After you convert to a script, you may still want a reproducible record of the original analysis notebook, environment and data. That’s where NoteCapsule helps.

from notebookcapsule import create_capsule

create_capsule(
    name="before-notebook-to-script",
    notebook_path="notebook.ipynb",
    data_dirs=["./data"],
    base_dir=".",  # project root
)

You can ship the cleaned-up script to production while keeping a Capsule of the original exploration for future reference.

Notebooks for exploration, Capsules for reproducibility

NoteCapsule lets you freeze a working notebook state before turning it into scripts, so you can always revisit how you got your results.

Join NoteCapsule early access