The basics
What is a PY file?
A .py file holds a program written in Python, a general-purpose programming language. It might be a ten-line script that renames photos, a module in a large web application, a data analysis, or a tool that came with some software you installed. The file is plain text, so any text editor can open it and show you the code.
To do anything, a Python file needs the Python interpreter: a program that reads the file and carries out its instructions. Nothing is compiled ahead of time into an .exe. That's what makes Python files easy to share and change, and why the person running one needs Python installed.
Python files come in a few related forms:
.py: ordinary source code, a script you run or a module other files import. Most Python files are this..pyw: the same thing, for Windows programs with a window of their own. Windows runs them withpythonw, which opens no console window..pyc: compiled bytecode that Python writes to a__pycache__folder to start faster next time. You never edit these, and deleting them is harmless..pyi: a stub file with only type hints, used by type checkers and IDEs. It never runs.
Anatomy
What's inside a Python file
A Python file is a list of statements that run from top to bottom, plus definitions (functions and classes) that run when something calls them. Indentation marks where each block starts and ends. Here is a small but complete script, part by part.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Greet people by name."""
import sys
DEFAULT_NAME = "world"
def greet(name: str = DEFAULT_NAME) -> str:
"""Return a greeting for one person."""
return f"Hello, {name}!"
class Greeter:
def __init__(self, names: list[str]) -> None:
self.names = names
def run(self) -> None:
for name in self.names:
print(greet(name))
def main() -> int:
Greeter(sys.argv[1:] or [DEFAULT_NAME]).run()
return 0
if __name__ == "__main__":
sys.exit(main())- 1
#!/usr/bin/env python3The shebang
Only used when the file is run as a program on macOS or Linux (
./greet.py): it tells the system to run it with the firstpython3on the PATH. The Windowspylauncher reads it too. Python itself treats it as a comment. - 2
# -*- coding: utf-8 -*-An encoding declaration
Optional, because UTF-8 has been the default since Python 3. You only need one for a file saved in another encoding, and it must be on line 1 or 2. The
-*-marks are an Emacs convention;# coding: latin-1works just as well. - 3
"""Greet people by name."""The docstring
A string as the first statement of a file, function or class is its documentation.
help(), IDEs and documentation tools show it. - 4
import sysAn import
Loads another module, here one from the standard library. Python looks in the script's own folder first, which is why a file of yours called
random.pyhides the realrandommodule. - 5
DEFAULT_NAME = "world"A constant, by convention
Python has no real constants. An upper-case name tells other programmers not to change it.
- 6
def greet(name: str = DEFAULT_NAME) -> str:A function with type hints
name: strand-> strdocument the types. Python doesn't enforce them at run time; checkers such as mypy and IDEs use them. - 7
return f"Hello, {name}!"Indentation is syntax
The four spaces put this line inside the function. There are no braces: an indent opens a block and the next line at the previous indent closes it. PEP 8 asks for four spaces per level.
- 8
class Greeter:A class
Bundles data (
self.names) with the methods that use it.__init__runs when you create one, asmain()does below. - 9
def main() -> int:A main function
Keeping the program's top-level steps in a function, rather than loose at the bottom of the file, means importing the file doesn't run them.
- 10
if __name__ == "__main__":The entry-point guard
Python sets
__name__to"__main__"for the file you run, and to the module's name when it's imported. This block therefore runs only when the file is executed directly. - 11
sys.exit(main())The exit status
Passes
main()'s return value to the operating system:0means success, anything else failure. Shell scripts and CI jobs check it.
Under the hood
What happens when you run a Python file
- 1You start the interpreter with the file:
python3 greet.pyon macOS or Linux,py greet.pyon Windows. - 2It decodes the bytes as text, as UTF-8 unless a
codingline on line 1 or 2 says otherwise. Bytes that aren't valid in that encoding stop it here with aSyntaxError. - 3It parses the whole file. A syntax error anywhere, even on the last line, means no line runs at all.
- 4It compiles the code to bytecode, simpler instructions for Python's virtual machine. For modules you import, it saves this as
__pycache__/name.cpython-315.pyc(the number is the Python version) and reuses it while the source is unchanged. The script you run directly isn't cached. - 5It runs the statements from top to bottom.
defandclassstatements create functions and classes; their bodies run only when called. Eachimportruns the imported file the first time. - 6It exits when the last statement has run, or when
sys.exit()or an uncaught exception ends it. An uncaught exception prints a traceback and exits with status 1.
Is Python compiled or interpreted?
Both, in a way. The standard interpreter, CPython, compiles every file to bytecode and then interprets the bytecode. The compiling happens automatically each time, so to you it behaves like an interpreted language.
How to run it
How to run a .py file on Windows, macOS and Linux
| Windows | macOS | Linux | |
|---|---|---|---|
| Get Python | The Python install manager, from python.org or the Microsoft Store | The installer from python.org, or a package manager such as Homebrew | Usually installed already; otherwise the python3 package |
| Run a file | py script.py or python script.py | python3 script.py | python3 script.py |
| Pick a version | py -V:3.14 script.py; py list shows what's installed | python3.14 script.py | python3.14 script.py |
| Run it as a program | Double-click, if .py is linked to Python; .pyw opens no console | chmod +x script.py, then ./script.py (needs a shebang) | chmod +x script.py, then ./script.py (needs a shebang) |
python3vspy. On macOS and Linux the command ispython3; plainpythonmay not exist, or on older systems may still mean Python 2. On Windows the recommended command ispy. The install manager also adds apython3command, but Python's documentation says it only exists to catch habits from other systems and isn't meant to be widely used.- Windows installers. The traditional python.org installer is deprecated since Python 3.14 and won't be produced from Python 3.16. The Python install manager replaces it.
- When a double-clicked script flashes and vanishes, it ran in a console window that closed when the script ended. Run it from a terminal (Command Prompt, PowerShell or Terminal) to see its output and any error.
- Inside a project, run files with the project's virtual environment active, so they see the packages installed for that project (see below).
The rules
Shebangs, encodings, file names and project layout
- Shebang.
#!/usr/bin/env python3finds whicheverpython3is first on the PATH, which includes an active virtual environment.#!/usr/bin/python3always uses the system's own copy. Either way the file needschmod +xto run as./script.py. - Encoding. Save files as UTF-8 and you need no declaration. A file in another encoding needs
# -*- coding: latin-1 -*-(or similar) on line 1 or 2, as set out in PEP 263. A UTF-8 byte order mark (BOM) is accepted by Python, but it stops the shebang working on macOS and Linux, because the file no longer starts with#!. - Line endings. Python reads LF, CRLF and CR line endings alike. The one place CRLF breaks things is the shebang line, as the errors table below shows.
- Indentation. Use spaces, four per level. Python refuses a file that mixes tabs and spaces in a way that makes the meaning ambiguous, with
TabError. - File names. PEP 8 asks for short, all-lowercase module names, with underscores if they help. A file you want to
importmust have a name that is a valid identifier:my-tool.pyruns fine but can't be imported, becauseimport my-toolis a syntax error. Don't name your files after standard library modules (random.py,email.py,string.py): they hide the real module from every import in that folder.
A larger program is a package: a folder of modules. __init__.py marks a folder as a regular package, __main__.py is what runs for python -m package, and pyproject.toml describes the project, its dependencies and the Python versions it supports. A common layout:
my-project/
pyproject.toml name, version, dependencies, Python version
src/
my_package/
__init__.py makes the folder an importable package
__main__.py runs with: python -m my_package
report.py a module: import my_package.report
tests/
test_report.py
.venv/ the virtual environment: never share or commit itVersions
Python 2 vs Python 3, and the versions that matter for files
A Python file doesn't say which version it was written for. You find out from the project's pyproject.toml (its requires-python field), from the README, or from the syntax. The big split is between Python 2 and 3, which can't run each other's files in general:
| Version | Released | What it means for a .py file |
|---|---|---|
| Python 2.7 | 2010; end of life 1 January 2020 | print "hello" without brackets, ASCII as the default source encoding, / dividing whole numbers as whole numbers. No longer maintained. |
| Python 3.0 | December 2008 | print() became a function, text strings became Unicode, UTF-8 became the default source encoding. |
| Python 3.6 | 2016 | f-strings: f"Hello, {name}". Files using them fail with a SyntaxError on older versions. |
| Python 3.10 | 2021 | The match statement and int | None type unions. |
| Python 3.14 | October 2025 | Template strings (t-strings). On Windows, the Python install manager replaces the old installer. |
| Python 3.15 | October 2026 | UTF-8 mode is on by default (PEP 686): open() without an encoding now reads and writes UTF-8 on every platform, where Windows used to use the system code page. |
Got an old script that fails with Missing parentheses in call to 'print'? It's Python 2 code. Small scripts can usually be fixed by hand; sample-python2.py below shows the typical differences.
Troubleshooting
Errors when opening or running a Python file
| Error message | Usual cause | Fix |
|---|---|---|
| 'python' is not recognized… / python: command not found | Python isn't installed, or the command has another name | Use py on Windows and python3 on macOS and Linux; install Python if neither works |
Typing python opens the Microsoft Store | A Windows app execution alias stands in for Python until it's installed | Install Python, then search the Start menu for "Manage app execution aliases" and check the Python entries |
| SyntaxError: Missing parentheses in call to 'print' | Python 2 code run with Python 3 | Update the code to Python 3 |
| TabError / IndentationError | Tabs and spaces mixed, or a line indented differently from its block | Let your editor convert tabs to four spaces |
| SyntaxError: Non-UTF-8 code starting with '\xe9' | The file was saved in an older encoding such as Windows-1252 | Re-save it as UTF-8, or add a coding line |
| ModuleNotFoundError: No module named 'requests' | The package isn't installed for the Python that's running the file | Activate the project's virtual environment, then python -m pip install requests |
| error: externally-managed-environment | pip install into the Python that a Linux distribution or Homebrew manages | Create a virtual environment and install there |
| /usr/bin/env: 'python3\r': No such file or directory | Windows (CRLF) line endings on a script run as ./script.py | Convert to LF with dos2unix or your editor |
| module 'random' has no attribute 'randint' | A file of yours called random.py hides the standard module (Python 3.13 and later add a hint saying so) | Rename your file and delete its .pyc in __pycache__ |
How to
How to open, edit and check a Python file
- Read or edit it: any plain-text editor works. Code editors such as VS Code (with its Python extension) or PyCharm add autocompletion, error highlighting and a debugger. IDLE, a simple editor, comes with Python from python.org. Avoid word processors, which can swap straight quotes for curly ones and break the code.
- Check the syntax without running it:
python3 -m py_compile file.pyreports the first syntax error (and writes a.pycto__pycache__if there is none). - Lint and format: Ruff or Pyflakes find likely bugs, mypy checks type hints, and Ruff or Black format code to the PEP 8 style.
- Keep each project's packages separate with a virtual environment, a folder holding a private copy of the interpreter's environment:
# macOS and Linux
python3 -m venv .venv
source .venv/bin/activate
python -m pip install requests
python script.py
# Windows (PowerShell or Command Prompt)
py -m venv .venv
.venv\Scripts\activate
python -m pip install requests
python script.pyList a project's packages in requirements.txt or pyproject.toml and share that, never the .venv folder itself: it contains paths that only work on the machine that made it.
Security
Is it safe to open or run a Python file?
Opening a .py file in a text editor only shows its code. Running it is different: Python has no sandbox, so a script can do anything your user account can, from reading your documents to installing software. Points worth knowing:
- Read before you run. Treat a script from a stranger like any other program. Code editors may offer to run project tasks when you open a folder; VS Code's Restricted Mode exists for opening code you don't trust yet.
- Packages run code too. Installing a package from source can run its build scripts, and a mistyped package name can install a look-alike. Check names and pin versions.
- Keep secrets out of
.pyfiles. API keys and passwords insettings.pyend up in version control and in every copy you share. Read them from environment variables or a secrets store, and remember.pycfiles contain the same strings. - Never
eval()orexec()text from users, and avoidsubprocesswithshell=Truearound user input, which lets crafted input run shell commands.pickle.load()on untrusted data can also run code.
Be wary of instructions to paste a command like python -c "…" or a downloaded script into a terminal to "fix" something. That runs code on your computer with your permissions.
Free downloads
Sample Python files to download
Free sample Python files for testing editors, linters, syntax highlighters, upload filters and size limits. All run with Python 3.10 or later and print their results, except sample-python2.py, which fails on purpose.
Loading…What's inside sample-script.py
The file is commented: open it in a text editor and each numbered comment marks one of these parts. Run it with python3 sample-script.py (or py sample-script.py on Windows); pass a text file's name to analyse that instead.
Comments 1 and 2: shebang and docstring
The
#!/usr/bin/env python3line, then a module docstring that doubles as usage instructions.Comments 3 and 4: imports and constants
Standard library imports only, so there's nothing to install, and upper-case constants including a multi-line sample text.
Comment 5: a dataclass
@dataclass(frozen=True)writes__init__and__repr__from the type-annotated fields, and a@propertycomputes the reading time.Comments 6 and 7: functions and files
Type hints, regular expressions and
collections.Counter, and a file read with an explicitencoding="utf-8".Comment 8: command-line arguments
argparsehandles an optional file name and a--topoption, and generates--helpfor free.Comments 9 and 10: errors and output
A missing or non-UTF-8 file produces a one-line message and exit status 1 instead of a traceback. f-strings format the results, with
:,and:.1fformat specs.Comment 11: the entry-point guard
if __name__ == "__main__":runsmain()only when the file is executed, so other code can importanalyse()without side effects.
All sample Python files
Commented sample script
sample-script.py · 3.9 KB (3,978 bytes)
A small command-line tool that counts words and sentences and estimates reading time, with numbered comments explaining each part. Passes Ruff's checks.
- Checking editors, highlighters and linters on modern Python
- Teaching the parts of a Python file
UTF-8 encoding test
sample-utf8.py · 1.9 KB (1,987 bytes)
Greetings in 12 languages plus symbols and emoji, a non-ASCII variable name, Unicode normalisation and
casefold(). Prints each string's length in characters and bytes.- Spotting encoding bugs in editors, pipelines and consoles
- Testing right-to-left and CJK text in code viewers
Windows (CRLF) line endings
sample-crlf.py · 852 bytes
A script with a shebang, saved with CRLF line endings.
python3 sample-crlf.pyworks;./sample-crlf.pyon macOS or Linux fails with thepython3\rerror.- Testing line-ending conversion in Git, editors and upload pipelines
- Reproducing the CRLF shebang error
UTF-8 with a byte order mark
sample-bom.py · 779 bytes
Starts with the bytes
EF BB BFbefore the shebang. Python runs it; running it as./sample-bom.pyfails because the file no longer starts with#!.- Checking whether a tool adds, keeps or strips a BOM
- Reproducing BOM problems with shebang lines
Python 2 code (deliberate syntax error)
sample-python2.py · 628 bytes
Python 2 syntax: a
printstatement,raw_input()andexcept ValueError, error. Clearly labelled; Python 3 stops at line 9 withMissing parentheses in call to 'print'.- Testing how editors, linters and CI report syntax errors
- Recognising Python 2 code
100 KB Python file
sample-100kb.py · 100 KB (102,400 bytes)
A table of Collatz stopping times for 1 to 21,841 and a function that checks every entry, padded with a comment to exactly 102,400 bytes.
- Upload and size-limit tests
- Parser, highlighter and editor performance
Ways to test with them
- Line endings: commit
sample-crlf.pyto Git or pass it through your pipeline, then check its bytes. If the CRLFs became LFs,./sample-crlf.pywill start working. - Encoding: open
sample-utf8.pyin your editor or viewer and run it; garbled text such asémeans something read the file as Windows-1252 instead of UTF-8. - Error reporting:
python3 -m py_compile sample-python2.pymust fail with line 9; use it to check that your linter, CI job or upload validator surfaces syntax errors. - Upload limits:
sample-100kb.pyis exactly 102,400 bytes, for testing a limit at the boundary. Some email services and filters block.pyattachments; the samples show where yours draws the line.
Free to use for testing, teaching and demos, commercially or not, with no attribution needed. A link back to this page is always appreciated.
Put it online
Have a Python file? Give it a link.
Drop a .py file on 99helpers and it gets its own address in seconds. Opening the link shows the code as plain text in the browser: it is never run on the server, which makes it a safe way to share a script for review or download.
Questions
Python files, frequently asked
What is a .py file?
A Python source file: a plain-text program written in the Python language. You run it with the Python interpreter, and you can read or edit it in any text editor.
How do I open a .py file?
To see or edit the code, open it in a text editor such as VS Code, Notepad or TextEdit. To run it, install Python and run py file.py on Windows or python3 file.py on macOS and Linux in a terminal.
Should I use python, python3 or py?
On macOS and Linux, use python3. On Windows, use py, which also lets you pick a version with py -V:3.14. Plain python works on Windows and inside an active virtual environment.
What are __pycache__ and .pyc files?
Compiled bytecode that Python saves the first time it imports a module, so it starts faster next time. They're safe to delete, and most projects keep them out of version control.
What does if __name__ == "__main__" mean?
The code under it runs only when the file is run directly, not when another file imports it. That lets one file work both as a script and as a module.
Can I turn a .py file into an .exe?
Not directly, because Python files need the interpreter. Tools such as PyInstaller bundle your script with a copy of Python into one executable, which runs on computers without Python installed.
Why does my script work in my editor but not from the terminal?
Usually two different Pythons: the editor uses a virtual environment with your packages installed, the terminal doesn't. Activate the environment first, or run the editor's interpreter by its full path.
Is it safe to run a .py file someone sent me?
Only if you trust the sender or have read the code. Python scripts run with your full user permissions and can read, change or send your files. Opening one in a text editor is safe.
Related formats
Other file types explained
Keep going
Related
Sources
- Python documentation: Using Python on Windows
- PEP 263: Defining Python Source Code Encodings
- PEP 8: Style Guide for Python Code
- PEP 3147: PYC Repository Directories
- PEP 686: Make UTF-8 mode default
- Python.org: Python source releases
Last reviewed 27 October 2026.