Last modified: Feb 08, 2026 By Alexander Williams
Convert Jupyter Notebook to Python Script
Jupyter Notebooks are fantastic for exploration and storytelling with code. But what happens when you need to run that code in a production environment or share it as a standard script? You need to convert it.
This guide covers all the methods to turn your .ipynb file into a clean .py Python script.
Why Convert a Jupyter Notebook?
Notebooks are interactive. They mix code, output, and markdown in one file. This is great for learning and analysis.
However, for automation, deployment, or version control, a plain Python script is often better. Scripts are lighter, easier to run headlessly, and fit into standard software pipelines.
Converting is essential for moving from prototype to production.
Method 1: Using Jupyter's Built-in Menu
This is the easiest way for beginners. Open your notebook in Jupyter Lab or Jupyter Notebook.
Navigate to the "File" menu. Select "Download as". Then choose "Python (.py)" from the dropdown list.
Your browser will download the script immediately. The file will have the same base name as your notebook.
This method is quick. But it offers no customization for the output.
Method 2: Command Line with nbconvert
The powerful and recommended method is using nbconvert. This is a command-line tool from the Jupyter ecosystem.
First, ensure you have it installed. It usually comes with Jupyter. You can check by running:
jupyter nbconvert --version
If not installed, get it with pip:
pip install nbconvert
Basic Conversion Command
To convert a notebook named `analysis.ipynb` to a script, use this command:
jupyter nbconvert --to script analysis.ipynb
This creates a new file called `analysis.py` in the same directory.
Useful nbconvert Options
You can customize the output with flags.
Use `--stdout` to print the script to the terminal instead of saving a file:
jupyter nbconvert --to script --stdout analysis.ipynb
Use `--output` or `-o` to specify a different output filename:
jupyter nbconvert --to script analysis.ipynb --output production_script.py
To exclude markdown cells and only get the code, use the `--no-prompt` and template options. This creates a cleaner script.
Method 3: Using Python Code (Programmatic Conversion)
You can convert notebooks from within another Python script. This is useful for automation.
Use the `nbformat` and `nbconvert` libraries. Here is an example script that performs the conversion.
# import_convert.py
import nbformat
from nbconvert import PythonExporter
# Define file paths
notebook_path = "my_notebook.ipynb"
script_path = "converted_script.py"
# 1. Read the notebook file
with open(notebook_path, 'r', encoding='utf-8') as f:
notebook_content = nbformat.read(f, as_version=4)
# 2. Create an exporter
exporter = PythonExporter()
# 3. Convert the notebook to Python source code
# The output is a tuple: (source_code, resources_dict)
(source_code, _) = exporter.from_notebook_node(notebook_content)
# 4. Write the source code to a .py file
with open(script_path, 'w', encoding='utf-8') as f:
f.write(source_code)
print(f"Successfully converted {notebook_path} to {script_path}")
python import_convert.py
Successfully converted my_notebook.ipynb to converted_script.py
This method gives you full control. You can filter cells or modify the code before saving.
What Gets Converted? Understanding the Output
It's important to know what your .py file will contain.
Code Cells: All Python code is transferred directly. Cell numbers (like `In[1]:`) may appear as comments if you don't use the `--no-prompt` flag.
Markdown Cells: These are turned into Python comments. Each line starts with a `#`.
Raw Output and Images: These are typically lost in the conversion. The script contains the code that *generates* the output, not the output itself. For saving figures, ensure your notebook code uses `plt.savefig()`.
Just as you might need a C to Python converter for legacy code, converting notebooks is about adapting format for a new purpose.
Cleaning the Converted Script
The raw conversion might have clutter. Here are tips for a production-ready script.
Remove Cell Metadata: Use `nbconvert` with a custom template or a post-processing script to strip out `In [ ]:` comments.
Handle Magic Commands: Notebooks use `%` magic commands (e.g., `%matplotlib inline`). These are IPython-specific. They will cause errors in a standard Python interpreter.
You must remove or replace them. For example, remove `%matplotlib inline`. For `%load_ext`, you may need to convert it to a standard import.
Consolidate Imports: Gather all import statements at the top of your script for better organization.
Define a Main Function: Wrap the main execution logic in a `if __name__ == "__main__":` block. This makes the script importable and more professional.
Example: Before and After Conversion
Let's see a simple notebook cell and its converted script form.
Notebook Cell (Markdown then Code):
# This cell calculates the square of numbers
numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers]
print(squares)
Converted .py File Content:
# In[1]:
# This cell calculates the square of numbers
numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers]
print(squares)
[1, 4, 9, 16, 25]
After cleaning, the final script might look like this:
"""
Script to calculate squares of a list.
Converted from Jupyter Notebook.
"""
def calculate_squares(input_list):
"""Return a list of squares for the given list."""
return [n**2 for n in input_list]
if __name__ == "__main__":
# Main execution logic
numbers = [1, 2, 3, 4, 5]
result = calculate_squares(numbers)
print(result)
This clean version is reusable, testable, and ready for automation.
Automating Conversion in Workflows
You can integrate notebook conversion into CI/CD pipelines. For example, use a GitHub Action that runs `nbconvert` on every commit.
This ensures your script is always up-to-date with the notebook. It's a best practice for MLOps projects.
Similarly, understanding data type conversion is key in Python, like using a Python convert int to binary method or learning how to perform a Python convert float to int operation.
Common Issues and Solutions
File Not Found Error: Ensure you are running the command in the correct directory that contains the .ipynb file.
Magic Command Errors: As noted, remove IPython magics. Use `--no-prompt` to help clean the output.
Large Output in Script: The conversion process itself is efficient. If your notebook is huge, the script will be large too. Focus on cleaning unnecessary comments.
Conclusion
Converting Jupyter Notebooks to Python scripts is a straightforward but vital skill. Use the Jupyter menu for a quick export. Use the command-line nbconvert tool for control and automation.
Remember to clean the resulting script. Remove magics and organize the code. This bridges the gap between data exploration and robust software.
Whether you're converting notebooks, Python convert images between file formats, or transforming data types, the principle is the same: use the right tool for the job to make your code portable and professional.
Start converting your notebooks today. Unlock the power to run your analyses anywhere.