How to Export Python Code
Exporting Python code usually means saving your work as a .py file that you can run, share, or move into another project. This guide shows you how to export Python code from a script, notebook, or editor without losing the parts needed to run it.
What you’ll build or solve
You’ll create a clean Python file that can run outside your current editor or notebook. Done means your code is saved as a .py file, includes required imports, and can be tested from the terminal.
Learn Python on Mimo
When this approach works best
Exporting Python code works best when:
- You want to move code from a notebook into a reusable script.
- You need to submit or share a Python file.
- You want to run code from the terminal instead of an interactive editor.
- You want to keep a clean version of working code for a project.
This is a bad idea if your code depends on hidden notebook state, missing files, or variables created in earlier cells. Clean the code first so the exported file can run from top to bottom.
Prerequisites
- Python installed
- A text editor, IDE, or notebook tool
- Basic knowledge of running Python files
- Code that already works in your current environment
No extra package is required for saving a normal .py file.
Step-by-step instructions
Step 1: Save the code as a .py file
Create a file with the .py extension. For example:
Bash
hello.py
Add your Python code:
Python
message = "Hello from Python"
print(message)
Run it from the terminal:
Bash
python hello.py
On some systems, you may need:
Bash
python3 hello.py
The exported file should include everything it needs to run. That means imports, variables, functions, and the code that starts the program.
A cleaner script often uses a main() function:
Python
def main():
message = "Hello from Python"
print(message)
if __name__ == "__main__":
main()
This pattern keeps your code organized and prevents it from running automatically when another file imports it.
What to look for
- The file ends with
.py. - The script runs from top to bottom without relying on hidden state.
- All required imports appear at the top.
- The terminal command runs from the folder that contains the file.
- Use
python3ifpythonpoints to a different version.
Step 2: Export code from a Jupyter notebook
If your code is in a Jupyter notebook, export it as a Python script.
In Jupyter Notebook or JupyterLab, use the menu:
File > Save and Export Notebook As > Executable Script
This creates a .py file from your notebook cells.
You can also use the terminal:
Bash
jupyter nbconvert --to script notebook.ipynb
This creates a file such as:
Bash
notebook.py
After exporting, open the file and clean it. Notebook exports often include comments, cell markers, or code that made sense only inside the notebook.
Example notebook-style code:
Python
data = [10, 20, 30]
sum(data)
Better script version:
Python
def main():
data = [10, 20, 30]
total = sum(data)
print(total)
if __name__ == "__main__":
main()
A notebook displays the result of sum(data) automatically. A script does not. Use print() when you want output in the terminal.
Step 3: Include files and dependencies
Python code may need packages or local files. Exporting the .py file alone may not be enough.
If your script imports packages, list them in a requirements.txt file:
requests
pandas
matplotlib
Someone else can install them with:
Bash
pip install -r requirements.txt
If your script reads a file, keep the file with the project:
Bash
project/
├── analysis.py
├── data.csv
└── requirements.txt
Then use a relative path:
Python
import csv
with open("data.csv", newline="") as file:
reader = csv.reader(file)
for row in reader:
print(row)
This makes the script easier to run on another computer.
Step 4: Test the exported file
Run the exported file from a fresh terminal.
Bash
python analysis.py
If it works only in your editor but fails in the terminal, the script may depend on editor settings, a different interpreter, or files in another folder.
Check the Python version:
Bash
python --version
Check the current folder:
Bash
pwd
On Windows PowerShell, use:
Get-Location
Then run the file from the correct project folder.
Examples you can copy
Example 1: Export a simple script
Python
def greet(name):
return f"Hello, {name}"
print(greet("Alex"))
Save it as:
Bash
greet.py
Run it:
Bash
python greet.py
This works well for small assignments and quick examples.
Example 2: Export reusable code with main()
Python
def calculate_total(prices):
return sum(prices)
def main():
prices = [12.99, 8.50, 4.25]
total = calculate_total(prices)
print(f"Total: {total}")
if __name__ == "__main__":
main()
This structure makes the function reusable from another file.
Example 3: Export notebook logic into a script
Notebook version:
Python
numbers = [2, 4, 6, 8]
sum(numbers) / len(numbers)
Script version:
Python
def average(numbers):
return sum(numbers) / len(numbers)
def main():
numbers = [2, 4, 6, 8]
result = average(numbers)
print(result)
if __name__ == "__main__":
main()
The script version prints the result, so it works from the terminal.
Example 4: Export code with a dependency
Python
import requests
def main():
response = requests.get("https://example.com")
print(response.status_code)
if __name__ == "__main__":
main()
Add this to requirements.txt:
requests
Install it before running the script:
Bash
pip install -r requirements.txt
Common mistakes and how to fix them
Mistake 1: Exporting code that depends on notebook state
What you might do:
Python
print(total)
Why it breaks:
total may have been created in an earlier notebook cell. The exported script does not know that unless the variable is defined before use.
Correct approach:
Python
prices = [10, 15, 20]
total = sum(prices)
print(total)
Make the file runnable from top to bottom.
Mistake 2: Forgetting to print results
What you might do:
Python
sum([1, 2, 3])
Why it breaks: A notebook may show the result automatically, but a Python script usually does not display expression results by itself.
Correct approach:
Python
result = sum([1, 2, 3])
print(result)
Use print() for terminal output.
Mistake 3: Sharing only the .py file without dependencies
What you might do:
Python
import pandas as pd
Why it breaks:
The code fails on another computer if pandas is not installed.
Correct approach:
pandas
Put required packages in requirements.txt and share it with the script.
Troubleshooting
If you see “No such file or directory,” run the command from the folder that contains the file.
If you see “ModuleNotFoundError,” install the missing package or activate the correct environment.
If python runs the wrong version, try python3 or check your interpreter path.
If the script works in your editor but not in the terminal, compare the working directory and Python interpreter.
If output does not appear, add print() around the value you want to see.
If you get a permission error, save the file in a folder where your user account can write and run files.
Quick recap
- Save exported Python code as a
.pyfile. - Include imports, variables, functions, and startup code.
- Use
print()for results you want to see in the terminal. - Export notebooks as scripts, then clean the code.
- Share dependencies in
requirements.txt. - Test the exported file from a fresh terminal.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot