File types · Explainer

The Python file (.py, .pyw)

A Python file is a plain-text program that the Python interpreter runs, on any operating system. This guide explains what's inside one, how to run it, the file-level rules and errors worth knowing, and has free sample Python files to download for testing.

At a glance

Full name
Python source file
Extensions
.py; .pyw for Windows programs without a console window; .pyi for type stubs; .pyc for compiled bytecode
MIME type
None registered; text/x-python is the usual one, and the one Python's own mimetypes module uses
Kind
Plain text (source code)
Encoding
UTF-8 by default since Python 3; another encoding needs a # coding: line
Language owner
Python Software Foundation; changes are proposed and agreed as PEPs
First released
1991, by Guido van Rossum at CWI in Amsterdam
Current version
Python 3.15 (October 2026); a new feature release comes out every October
Runs with
python3 on macOS and Linux, py or python on Windows
Magic number
None; often starts with a #! line. Compiled .pyc files start with a 4-byte, version-specific number

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 with pythonw, 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.

greet.py
#!/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. 1#!/usr/bin/env python3

    The 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 first python3 on the PATH. The Windows py launcher reads it too. Python itself treats it as a comment.

  2. 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-1 works just as well.

  3. 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. 4import sys

    An 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.py hides the real random module.

  5. 5DEFAULT_NAME = "world"

    A constant, by convention

    Python has no real constants. An upper-case name tells other programmers not to change it.

  6. 6def greet(name: str = DEFAULT_NAME) -> str:

    A function with type hints

    name: str and -> str document the types. Python doesn't enforce them at run time; checkers such as mypy and IDEs use them.

  7. 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. 8class Greeter:

    A class

    Bundles data (self.names) with the methods that use it. __init__ runs when you create one, as main() does below.

  9. 9def 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. 10if __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. 11sys.exit(main())

    The exit status

    Passes main()'s return value to the operating system: 0 means success, anything else failure. Shell scripts and CI jobs check it.

Under the hood

What happens when you run a Python file

  1. 1You start the interpreter with the file: python3 greet.py on macOS or Linux, py greet.py on Windows.
  2. 2It decodes the bytes as text, as UTF-8 unless a coding line on line 1 or 2 says otherwise. Bytes that aren't valid in that encoding stop it here with a SyntaxError.
  3. 3It parses the whole file. A syntax error anywhere, even on the last line, means no line runs at all.
  4. 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.
  5. 5It runs the statements from top to bottom. def and class statements create functions and classes; their bodies run only when called. Each import runs the imported file the first time.
  6. 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

WindowsmacOSLinux
Get PythonThe Python install manager, from python.org or the Microsoft StoreThe installer from python.org, or a package manager such as HomebrewUsually installed already; otherwise the python3 package
Run a filepy script.py or python script.pypython3 script.pypython3 script.py
Pick a versionpy -V:3.14 script.py; py list shows what's installedpython3.14 script.pypython3.14 script.py
Run it as a programDouble-click, if .py is linked to Python; .pyw opens no consolechmod +x script.py, then ./script.py (needs a shebang)chmod +x script.py, then ./script.py (needs a shebang)
  • python3 vs py. On macOS and Linux the command is python3; plain python may not exist, or on older systems may still mean Python 2. On Windows the recommended command is py. The install manager also adds a python3 command, 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 python3 finds whichever python3 is first on the PATH, which includes an active virtual environment. #!/usr/bin/python3 always uses the system's own copy. Either way the file needs chmod +x to 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 import must have a name that is a valid identifier: my-tool.py runs fine but can't be imported, because import my-tool is 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:

project 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 it

Versions

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:

VersionReleasedWhat it means for a .py file
Python 2.72010; end of life 1 January 2020print "hello" without brackets, ASCII as the default source encoding, / dividing whole numbers as whole numbers. No longer maintained.
Python 3.0December 2008print() became a function, text strings became Unicode, UTF-8 became the default source encoding.
Python 3.62016f-strings: f"Hello, {name}". Files using them fail with a SyntaxError on older versions.
Python 3.102021The match statement and int | None type unions.
Python 3.14October 2025Template strings (t-strings). On Windows, the Python install manager replaces the old installer.
Python 3.15October 2026UTF-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 messageUsual causeFix
'python' is not recognized… / python: command not foundPython isn't installed, or the command has another nameUse py on Windows and python3 on macOS and Linux; install Python if neither works
Typing python opens the Microsoft StoreA Windows app execution alias stands in for Python until it's installedInstall 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 3Update the code to Python 3
TabError / IndentationErrorTabs and spaces mixed, or a line indented differently from its blockLet 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-1252Re-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 fileActivate the project's virtual environment, then python -m pip install requests
error: externally-managed-environmentpip install into the Python that a Linux distribution or Homebrew managesCreate a virtual environment and install there
/usr/bin/env: 'python3\r': No such file or directoryWindows (CRLF) line endings on a script run as ./script.pyConvert 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.py reports the first syntax error (and writes a .pyc to __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:
terminal
# 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.py

List 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 .py files. API keys and passwords in settings.py end up in version control and in every copy you share. Read them from environment variables or a secrets store, and remember .pyc files contain the same strings.
  • Never eval() or exec() text from users, and avoid subprocess with shell=True around 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.

sample-script.py · 3.9 KBDownloadOpen
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.

  1. Comments 1 and 2: shebang and docstring

    The #!/usr/bin/env python3 line, then a module docstring that doubles as usage instructions.

  2. 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.

  3. Comment 5: a dataclass

    @dataclass(frozen=True) writes __init__ and __repr__ from the type-annotated fields, and a @property computes the reading time.

  4. Comments 6 and 7: functions and files

    Type hints, regular expressions and collections.Counter, and a file read with an explicit encoding="utf-8".

  5. Comment 8: command-line arguments

    argparse handles an optional file name and a --top option, and generates --help for free.

  6. 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 :.1f format specs.

  7. Comment 11: the entry-point guard

    if __name__ == "__main__": runs main() only when the file is executed, so other code can import analyse() 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.py works; ./sample-crlf.py on macOS or Linux fails with the python3\r error.

    • 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 BF before the shebang. Python runs it; running it as ./sample-bom.py fails 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 print statement, raw_input() and except ValueError, error. Clearly labelled; Python 3 stops at line 9 with Missing 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.py to Git or pass it through your pipeline, then check its bytes. If the CRLFs became LFs, ./sample-crlf.py will start working.
  • Encoding: open sample-utf8.py in 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.py must fail with line 9; use it to check that your linter, CI job or upload validator surfaces syntax errors.
  • Upload limits: sample-100kb.py is exactly 102,400 bytes, for testing a limit at the boundary. Some email services and filters block .py attachments; 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

Last reviewed 27 October 2026.