How to Save a Python File

To save a Python file, write your code in a plain-text editor and save it with a .py extension, such as hello.py. Make sure the editor hasn’t added .txt to the filename. This guide covers saving and running a script, fixing common saving problems, and saving text or other data from inside a Python program.

What Saving a Python File Means

A Python script is a plain-text file containing Python code. The .py extension identifies it as Python source code; you don’t need a special document format.

“Saving in Python” can mean two different things:

  • Saving your code: Store the instructions you write in a file that you can edit and run later.
  • Saving your program’s data: Have your code write results, text, or other information to a separate file.

Saving your script preserves its instructions, not the results produced when it runs. If you want to keep those results, your program needs to write them somewhere.

How to Save and Run a Python Script

Choose an editor based on what you already have available.

Editor When to Choose It
IDLE You want a Python-focused editor with a built-in way to run scripts.
Visual Studio Code You already use it or want to organize scripts in a project folder.
Notepad on Windows You need a straightforward way to create a plain-text script.
TextEdit on macOS You want to use a built-in editor and can switch it to plain-text mode.

Step 1: Create a Plain-Text Document

  1. Open a new document in your editor: – In IDLE, choose File > New File. – In VS Code, choose File > New Text File. – In Notepad or TextEdit, choose File > New.
  2. If you use TextEdit, choose Format > Make Plain Text if that option is available. If the menu instead offers Make Rich Text, the document is already plain text.
  3. Enter this small test program:
print("Hello, world!")

Use a code editor or plain-text editor rather than a word processor. Rich-text formatting can add information that isn’t valid Python code.

Step 2: Save the File With a Python Extension

  1. In the IDLE editor, choose File > Save As to save the current window to a file. The same menu path works in VS Code and Notepad. For a new TextEdit document, choose File > Save.
  2. Choose a folder you can find again, such as a dedicated project folder.
  3. Enter hello.py as the filename.
  4. Apply any editor-specific options: – Notepad: Set Save as type to All files so the editor doesn’t append a text-file extension. – TextEdit: Keep the .py extension if prompted to choose between it and .txt.
  5. Click Save.

For later changes, use Ctrl+S on Windows or Linux, or Command+S on macOS. Saving updates the existing file; use Save As when you want a separate copy or a different filename.

Step 3: Check the Actual Filename

  1. Locate the saved file in your file manager.
  2. Make sure the full name is hello.py, not hello.py.txt. In Windows 11 File Explorer, enable View > Show > File name extensions to reveal hidden extensions.
  3. Open the file in your editor and confirm that it contains the code you entered.

If the filename ends in .py.txt, remove the trailing .txt. Accept the extension-change confirmation if Windows displays one.

The file’s icon is not a reliable check. An association with Notepad or another application doesn’t stop a correctly saved script from being a Python file.

Step 4: Run the Saved Script

  1. With hello.py open in IDLE’s editor, choose Run > Run Module or press F5. To use a terminal instead, open it in the folder containing hello.py. In VS Code, opening your project with File > Open Folder and choosing Terminal > New Terminal normally starts the terminal in that project folder.

On Windows, with the Python launcher available:

py hello.py

On macOS or Linux, with Python 3 installed:

python3 hello.py
  1. Confirm that hello.py prints this greeting: “`text Hello, world! “`
Hello, world!

You can create and save a script without installing Python, but running it requires a working Python interpreter. If the terminal doesn’t recognize the command, that is an installation or command-availability problem, not evidence that the file was saved incorrectly.

How to Save Text From Inside Python

To save text generated by a program, open a destination file, write the string, and close the file. The general opening syntax is:

File_object = open("File_Name", "Access_Mode")

Replace the filename and access-mode placeholders with actual values. The important modes are:

  • w: Create a file for writing, or erase the existing contents if the file already exists.
  • a: Append new content to the end without erasing existing content.
  • x: Create a new file, but raise an error rather than overwrite an existing one.
  • r: Read an existing file; this is the default if you omit the mode.

For an opened text file, the syntax for writing one string is:

File_object.write(str1)

Here, str1 represents the string you want to write. The method doesn’t automatically add a line break; include \n when you need one.

Write and Close a Text File

Use a with statement so Python closes the file automatically when the block ends, including when an exception occurs.

The following example replaces any existing notes.txt in the working directory. Change the mode to x if you want to prevent accidental overwriting.

from pathlib import Path

destination = Path("notes.txt")

with open(destination, "w", encoding="utf-8") as file:
    file.write("Hello from Python!\n")

print(f"Saved to: {destination.resolve()}")

The explicit encoding makes the text format predictable.

Save this code as a script and run it. Then open the printed location in a text editor and confirm that the file contains the greeting.

Find Where Python Saved the File

A relative filename such as notes.txt is resolved against the program’s current working directory. That directory is not necessarily the folder containing the script, an IDE, notebook, or terminal can start the program elsewhere.

The example prints the destination’s full path so you can find the file without guessing.

If you need a different destination, give Path an absolute path to a folder that already exists. Opening a file can create the file itself, but it does not create missing parent folders.

How to Save JSON, CSV, and Python Objects

Choose a format based on what you need to preserve. JSON suits common structured data, CSV suits rows and columns, and pickle can preserve a broader range of Python objects.

Save Structured Data as JSON

Use JSON for data such as dictionaries, lists, strings, numbers, and Boolean values that other programs may also need to read. Open the JSON file using UTF-8 encoding.

import json

settings = {
    "name": "Ada",
    "notifications_enabled": True
}

with open("settings.json", "w", encoding="utf-8") as file:
    json.dump(settings, file)

After running the script, open settings.json in a text editor and confirm that it contains the saved settings. JSON uses its own syntax, so Python’s True appears as true.

Not every Python object can be written directly as JSON. For example, convert a set to a list before saving it, or choose a format appropriate to that object.

Save Rows and Columns as CSV

Use Python’s csv module rather than joining values with commas yourself. The module handles details such as quoting fields that contain commas.

import csv

rows = [
    ["name", "language"],
    ["Ada", "Python"]
]

with open("people.csv", "w", newline='', encoding="utf-8") as file:
    writer = csv.writer(file)
    writer.writerows(rows)

The newline='' option lets the CSV module handle newline characters correctly and avoids extra carriage returns or blank rows on some platforms. Use this option when opening CSV files for either reading or writing with the module.

Run the script, then open people.csv in a spreadsheet application or text editor. Confirm that the header and data appear as separate rows with the expected columns.

Save Python-Specific Objects With Pickle

Pickle is useful when you need to preserve Python objects that JSON doesn’t directly support, such as sets. It uses binary files rather than text files.

Default pickle protocols vary across recent Python versions: Python 3.8–3.13 use protocol 4, while Python 3.14 uses protocol 5. For a shared pickle file, choose a protocol supported by both the Python version writing it and the version reading it, using the pickle documentation to check compatibility.

Only unpickle data from a trusted source that hasn’t been tampered with. Loading a malicious pickle file can execute arbitrary code.

import pickle

data = {
    "tags": {"python", "files"}
}

with open("state.pkl", "wb") as file:
    pickle.dump(data, file)

with open("state.pkl", "rb") as file:
    restored = pickle.load(file)

print(restored == data)

The binary modes are required for this operation. The pickle example prints True if the restored data matches the original data.

For information that needs to move between Python and other languages, prefer a portable format such as JSON.

Common Python File-Saving Problems

Match the symptom to its likely cause before changing the code or reinstalling anything.

Symptom Likely Cause Fix
The script is named hello.py.txt The editor appended a text extension, possibly hidden by the file manager. Show filename extensions and remove the trailing .txt.
Python reports that it can’t open the script The terminal is in the wrong folder, or the filename is different. Open the terminal in the script’s folder and check the exact filename.
A save operation raises PermissionError The destination isn’t writable, or another process is preventing access. Choose a writable project folder; close an application that is locking the file if necessary.
Writing a file raises FileNotFoundError A parent folder in the destination path doesn’t exist. Create the parent folder or choose an existing one.
The output file seems to be missing The program wrote it to a different working directory. Print the destination’s resolved path and open that location.
The file saves, but running it produces a syntax error Saving succeeded, but the contents aren’t valid Python. Read the error’s line number and correct the code, including any copied prompts or rich-text characters.
Double-clicking the script makes a window disappear The program may finish or fail before you can read its output. Run it in IDLE or an already-open terminal so the output remains visible.

If you accidentally overwrite a file, saving again won’t recover the previous contents. Check your editor’s undo history, local file history, backups, or version control before making further changes.

How to Confirm Your File Is Saved

Before closing the editor or moving on to another task, make these checks:

  • The file exists on disk. Don’t rely solely on an open editor tab.
  • The latest edits are saved. An unsaved-change marker, often a dot or asterisk, should disappear after saving.
  • The contents reopen correctly. Check the actual file, not just a different tab with a similar name.
  • The script runs as expected. Successful saving and correct program behavior are separate checks.
  • Any generated data is present. Inspect the destination file or read it back to verify its contents.

Keep your script in a project folder and use version control or backups for work you want to preserve. Make your next edit, save it, and rerun the script to check the updated behavior.

Frequently Asked Questions

Is There a Python save() Command?

Python has no universal built-in save() command for saving scripts or arbitrary data. Save source code through your editor, and use file-writing functions or a suitable serialization module for program data. Some libraries provide their own methods named save, but those methods belong to the library rather than to Python itself.

How Do I Save a Text File as a Python File?

If the text file already contains Python code, open it in a plain-text editor and use File > Save As to give it a filename ending in .py. You can also rename an existing plain-text file’s extension from .txt to .py. Changing the extension doesn’t turn ordinary prose or rich-text formatting into valid Python code.

How Do I Save Code From the Python Shell?

Copy the statements you want to keep into a new editor document, remove shell prompts such as >>> and ..., and save the document with a .py extension. Keep only the code, not the output printed beneath it, and preserve indentation inside functions, loops, and other blocks. Run the saved script to confirm that it works independently of variables left over from the interactive session.

How Do You Save Something in Python?

Save Python code by placing it in a text editor and naming the file with a .py extension. To keep text produced by a program, open an output file in write mode, call write(), and use a with block so the file is closed automatically.