How to Save a Python File and Export Program Data
Save a Python script as a plain-text file with a .py extension, such as hello.py. You can create it in any code editor, save it into a project folder, and then run it with the Python interpreter. Saving source code is different from saving data your program produces, so this guide covers both.
What Saving a Python File Means
A Python file is normally a text file containing Python source code. The .py extension tells editors, operating systems, and tools that the file should be treated as Python code.
For example, this file should be saved as hello.py:
print("Hello, world!")
The filename matters:
hello.pyis a Python script.hello.txtis a text file, even if it contains Python code.hello.py.txtis usually a text file with a misleading name.hello.ipynbis a Jupyter Notebook, not a standard Python script.
On Windows, File Explorer can hide known file extensions. Turn on View > Show > File name extensions before renaming files so you can confirm the file really ends in .py.
How to Save a Python Script
Use this table to choose the right save action before you start.
| What You Need | Best Action | Result |
|---|---|---|
| Create a new program | Save As with a .py name |
Creates a Python script in your chosen folder |
| Save edits to an existing script | Save | Updates the same .py file |
| Make a separate version | Save As with a new .py name |
Keeps the original and creates a copy |
| Run a quick experiment | Create a new file in a project folder | Keeps test code out of unrelated folders |
Step 1: Create a Project Folder and Name the File
Create a folder for the project before creating the script. A simple folder structure prevents source code, downloads, generated files, and notes from becoming mixed together.
For example, create a folder named python-project, then open that folder in your editor.
In common editors, use one of these paths:
- Visual Studio Code: File > Save As
- IDLE: File > Save As
- Use your editor’s file-creation and save options.
Enter a descriptive filename ending in .py, such as:
hello.py
If the save dialog has a file-type selector, choose a plain-text or all-files option rather than a format that automatically adds .txt.
Step 2: Write the Code and Save It
Add Python code to the file. For a first test, use this:
def greet(name):
return f"Hello, {name}!"
print(greet("Python"))
Save the file with:
- Ctrl+S on Windows or Linux
- Command+S on macOS
Most editors show an unsaved indicator in the tab or title bar. Save again whenever you make changes before running the script.
Step 3: Run the Saved Script
Open a terminal in the folder containing the file.
On Windows, run:
py hello.py
On macOS or Linux, run:
python3 hello.py
You should see:
Hello, Python!
That output confirms that Python found and executed the saved hello.py file.
Where to Save Python Files
Keep each project in its own folder. This makes imports, virtual environments, version control, test files, and generated output easier to manage.
A small project can start like this:
python-project/
├── hello.py
├── README.md
├── data/
├── output/
└── tests/
Use the project folder as the place where you open your editor and terminal. When code refers to a relative path such as data/users.json, Python resolves it from the directory where you run the program.
Avoid saving your own scripts inside the Python installation folder or package folders such as site-packages. Those directories are managed by Python and package installers, and updates can overwrite files there.
For larger projects, place application code in a dedicated folder such as src/ or use a package directory:
weather-app/
├── src/
│ └── weather_app/
│ └── main.py
├── tests/
└── pyproject.toml
A predictable project folder is more useful than a complicated naming system. Start with a clear folder, meaningful filenames, and separate locations for source code and generated output.
How to Save Data From Python
Saving Python code and saving the data it produces are separate operations. You save source code in a .py file through your editor; your running program saves output by opening or creating files.
Use the file mode that matches what you need.
| Mode | Use It When | What Happens if the File Exists |
|---|---|---|
"w" |
You want a fresh file or replacement output | Existing contents are erased |
"a" |
You want to add data to the end | Existing contents are kept |
"x" |
You want to create a new file without overwriting one | Python raises FileExistsError |
"wb" |
You are writing raw bytes, such as downloaded binary data | Existing contents are erased |
Save a Text File
Use a with block so Python closes the file after writing, including when an error occurs inside the block.
message = "Build completed successfully.\n"
with open(
"output.txt",
"w",
encoding="utf-8",
newline="\n",
) as file:
file.write(message)
Pass encoding="utf-8" when opening text files so characters are stored with a consistent, widely supported encoding. Passing newline="\n" controls text newline handling and writes line breaks consistently.
The "w" mode creates output.txt if it does not exist. If it already exists, "w" replaces its contents.
Append Instead of Replacing Data
Use append mode when each program run should add a new record without deleting prior output.
with open("events.log", "a", encoding="utf-8") as file:
file.write("Application started\n")
This creates events.log if necessary and writes each new entry at the end of the file.
Create a File Without Accidental Overwrites
If a file must be new, use exclusive creation mode:
with open("new-report.txt", "x", encoding="utf-8") as file:
file.write("Initial report contents\n")
If new-report.txt already exists, Python stops with FileExistsError instead of replacing it.
You can also create or update an empty file path with pathlib:
from pathlib import Path
Path("run.marker").touch(mode=0o666, exist_ok=True)
Path.touch(mode=0o666, exist_ok=True) creates the file when it is missing and does not fail when it already exists. It is useful for marker files, log files, and setup scripts, but it does not write program content by itself.
Save Structured Data as JSON
Use JSON when you need to preserve dictionaries, lists, strings, numbers, booleans, and null values in a format other programs can read.
import json
settings = {
"theme": "dark",
"notifications": True,
"recent_projects": ["api", "dashboard"],
}
with open("settings.json", "w", encoding="utf-8") as file:
json.dump(settings, file)
This creates a settings.json file in the current working directory. Use a .json extension so it is recognizable as JSON data rather than Python source code.
How to Save a Jupyter Notebook as a Python File
A Jupyter Notebook is saved as an .ipynb file, which stores code cells, Markdown cells, cell outputs, and notebook metadata. Exporting it as .py creates a regular Python script containing the code.
From the directory containing your notebook, run:
jupyter nbconvert --to script analysis.ipynb
Open the exported .py file and review it before relying on it. Make any changes needed before running the exported script from a terminal.
Keep the original .ipynb file if you want to preserve outputs, visualizations, and explanatory Markdown.
Check That Your Python File Saved Correctly
Use this short checklist after saving a script or data file:
- Confirm the filename ends in
.pyfor Python source code. - Check that the file appears in the intended project folder.
- Reopen the file in your editor and confirm the latest changes are present.
- Run the script from the project folder.
- Check the terminal for expected output or errors.
- For generated files, open the output file and confirm it contains the expected text or structured data.
If Python reports that it cannot open the file, the usual cause is that the terminal is in a different folder from the script. Open a terminal in the project folder or navigate to the folder before running the command.
Frequently Asked Questions
How do I save a Python script as .py in Python 3.12?
Saving a Python script works the same way in Python 3.12 as in other current Python versions: save plain text with a .py extension, such as program.py. The Python version affects how you run and interpret the script, not how you save the source file.
On Windows, you can explicitly run the script with Python 3.12 using:
py -3.12 program.py
How Do I Save a Copy of a Python File?
Use File > Save As in your editor, then give the copy a different name such as calculator_backup.py. This keeps the original file unchanged and creates a separate editable script.
To copy a Python file from within another Python program without overwriting an existing backup, use:
from pathlib import Path
from shutil import copy2
source = Path("calculator.py")
destination = Path("calculator_backup.py")
if destination.exists():
raise FileExistsError(f"{destination} already exists")
copy2(source, destination)
Can I Use Notepad or Another Basic Editor to Save Python Files?
Yes. Any editor that saves plain text can create Python files, including Notepad, VS Code, IDLE, and PyCharm. Save the file with a .py extension and avoid rich-text editors that add formatting, fonts, or document markup.
A program can save text output by opening a file in write mode and calling write() inside a with block.
