Convert Jupyter Notebook (.ipynb) to Python script (.py)
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
- Open your notebook in classic Jupyter Notebook.
- File → Download as → Python (.py).
- You’ll get a
notebook.pyfile 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
- Remove exploratory cells, debug prints and commented-out code.
- Move configuration to the top (paths, hyperparameters, etc.).
- Wrap logic in functions and a
if __name__ == "__main__":block.
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