Notebook work often starts as exploratory cells, but code reviews, schedulers, and source-control diffs usually need a plain Python file. nbconvert can export a Python notebook into a .py script so the same code can move out of the browser-based notebook interface.
The Python exporter writes code cells, markdown cells as comments, and notebook cell markers into a script with the same base name as the notebook. Treat the generated file as a handoff artifact before committing or scheduling it, because cell order, hidden notebook state, and notebook-only syntax can change how it behaves outside Jupyter.
Use the Python export when the next step is editing, reviewing, or running notebook code as a script. If the narrative text, saved output, or rendered charts matter more than executable code, export the notebook to Markdown or HTML instead.
nbconvert reads the saved .ipynb file. It does not execute cells before exporting unless --execute is added.
Related: How to execute a Jupyter Notebook from the command line
$ jupyter nbconvert --to python analysis-demo.ipynb [NbConvertApp] Converting notebook analysis-demo.ipynb to python [NbConvertApp] Writing 209 bytes to analysis-demo.py
Replace analysis-demo.ipynb with the notebook to export. The generated script keeps the same base name and uses .py.
$ ls -lh analysis-demo.py -rw-r--r-- 1 user user 209 Jul 6 12:35 analysis-demo.py
#!/usr/bin/env python # coding: utf-8 # # Analysis script demo # # Prepare notebook code for script review. # In[ ]: rows = [2, 4, 6] print(f'Total rows: {len(rows)}') print(f'Total value: {sum(rows)}')
$ python -m py_compile analysis-demo.py
No output means Python parsed the generated script without a syntax error.
$ python analysis-demo.py Total rows: 3 Total value: 12
Notebook cells that use IPython magics, shell escapes, widgets, display hooks, or hidden session state may need edits before the generated file runs as a normal Python script.