PY File Documentation


Summary

A Python Script file holds source code written in the Python language, created by Guido van Rossum in 1991. Its extension is .py and its MIME type is text/x-python. Any editor opens the plain UTF-8 text, but running it needs a Python interpreter: type python file.py in a terminal. It is human-readable code, not a finished program, so the two common questions are how to run it and how to bundle it into an .exe.

Technical details

FeatureValue
Full namePython Source Code File
File extension.py
MIME typetext/x-python
Format typePlain-text source code
DeveloperPython Software Foundation (language by Guido van Rossum)
Introduced1991 (Python 0.9.0); PSF steward since 2001
Reference implementationCPython (also PyPy, Jython, IronPython)
Default encodingUTF-8 (PEP 3120); overridable with a coding declaration
ExecutionInterpreted; compiled to bytecode cached as .pyc
Line structureSignificant indentation defines blocks (no braces)
Human-readableYes — editable in any text editor
SignatureNone (plain text); optional shebang or UTF-8 BOM EF BB BF
Language generationsPython 2 (EOL 1 Jan 2020) and Python 3 (current, incompatible)
Open standardYes — open-source language and reference interpreter
ParadigmsProcedural, object-oriented, functional
Package installerpip, from the Python Package Index (PyPI)
Related extensions.pyc, .pyw, .pyi, .pyd, .pyz, .ipynb
Specificationdocs.python.org/3/reference/
Structure at a glance

A .py file is plain UTF-8 text with no binary signature. On Unix the first line is often a shebang, #!/usr/bin/env python3, which tells the shell which interpreter to run. Blocks are defined by indentation (conventionally four spaces), not by braces, so a wrong indent is a real syntax error. Modules are pulled in with import; logic lives in def functions and class definitions; and code guarded by if __name__ == "__main__": runs only when the file is executed directly, not when it is imported.

What is a PY file?

A .py file holds source code written in Python, the high-level programming language created by Guido van Rossum and first released in 1991. It is an ordinary UTF-8 text file: open it in any editor and you can read every line. The file only becomes a running program when it is fed to a Python interpreter, the reference one being CPython from python.org (alternatives include PyPy, Jython and IronPython). Because Python is interpreted and cross-platform, the same .py runs unchanged on Windows, macOS and Linux as long as Python and any imported libraries are present.

Python code stands out for its clean, readable syntax. Where many languages use braces and semicolons, Python uses indentation to mark structure, which forces a consistent layout. A short example:

def greet(name):
    return "Hello, " + name + "!"

The function greet takes one argument and returns a string. There are no semicolons or curly braces; the indented line is the function body. The same syntax supports procedural, object-oriented and functional styles, which is part of why .py files are used across web back ends (Django, Flask, FastAPI), data science and machine learning (NumPy, pandas, PyTorch), automation, and teaching.

The anatomy of a .py file: shebang, imports, definitions, __main__

A well-formed script tends to follow the same top-to-bottom shape, and each part has a defined job.

#!/usr/bin/env python3        # shebang (Unix): which interpreter runs the file
# -*- coding: utf-8 -*-       # optional encoding declaration
import sys                    # standard-library / third-party modules
from pathlib import Path

CONFIG = "settings.ini"       # module-level constants and state

def main(argv):               # function definitions: the program logic
    ...

class Report:                 # class definitions
    ...

if __name__ == "__main__":    # runs only when executed directly
    main(sys.argv)

The optional first line, the shebang (#!/usr/bin/env python3), is read by the Unix shell, not by Python: it tells the OS which interpreter to launch when the file is run as an executable. Windows ignores it, but the py launcher reads it to pick a version. An encoding declaration such as coding: utf-8 only matters when the source is not already UTF-8, which since Python 3 is the default anyway (PEP 3120).

The import statements pull in other modules. def and class statements are executed too, but executing them merely binds a name to a function or class object; the body inside runs later, when the function is called. The final block, if __name__ == "__main__":, is the idiom that distinguishes a script from a module. When you run python file.py, Python sets the special variable __name__ to the string "__main__" in that file, so the guarded code runs. When the same file is imported by another module, __name__ is instead the module’s own name, so the guarded code stays silent and only its functions and classes are exposed. That single line is what lets one file act as both a runnable program and a reusable library.

How the interpreter runs a .py file

Running a script is one command. Install Python from python.org (tick “Add to PATH” on Windows), open a terminal in the file’s folder, and type python file.py on Windows or python3 file.py on macOS and Linux. Double-clicking a .py on Windows also works if the py launcher is installed, but a script that finishes or crashes closes its console instantly, so the output vanishes; running from an already-open terminal lets you read the result or the traceback. Adding input() at the end, or using the .pyw extension for GUI scripts, avoids the flashing-window problem.

Behind the command, CPython does not execute the text line by line as characters. It first compiles the source to an intermediate bytecode and then runs that bytecode on the CPython virtual machine. For a top-level script the bytecode is thrown away after the run, but when a module is imported, CPython caches the compiled result so the next import is faster.

Compilation to bytecode and the __pycache__ / .pyc cache

When CPython imports a module, it compiles the .py to bytecode and writes that to a .pyc file inside a __pycache__ folder next to the source. The file name records the interpreter, for example report.cpython-312.pyc, so different Python versions can coexist without clobbering each other’s caches.

A .pyc begins with a 16-byte header (four 32-bit little-endian words). Bytes 0–3 are a magic number that identifies the exact CPython version that wrote the file; bytes 4–7 are a bit-field of flags introduced by PEP 552; bytes 8–11 hold the source file’s modification timestamp; bytes 12–15 hold its size. From byte 16 onward is the marshalled code object. On import, CPython checks the magic number and the timestamp/size against the current interpreter and the current .py; if either fails, it recompiles. This is why moving a .pyc to a different Python version triggers a “bad magic number” error, and why the .py remains the single source of truth: the cache is only a startup optimisation, not real source protection. You can force compilation with python -m py_compile file.py. (Separate .pyo optimised files were merged into .pyc in Python 3.5.)

Python 2 versus Python 3: why a script won’t run

There are two partly incompatible generations of the language, and the mismatch is a frequent cause of “my script won’t run”. Python 2 reached end-of-life on 1 January 2020 and is no longer supported; Python 3 is current. They are not interchangeable. The most visible break is print: in Python 2 it was a statement (print x), while in Python 3 it is a function (print(x)), so Python 2 code raises a SyntaxError under Python 3 and vice versa. Integer division, Unicode string handling and many standard-library module names also changed. If a downloaded script fails immediately, check which generation it targets before anything else.

Two other errors dominate. If Python is not installed or not on PATH, the shell reports “command not found”. If a required third-party library is missing, Python raises ModuleNotFoundError: No module named 'x', fixed with pip install x. Libraries live on the Python Package Index (PyPI) and install into the interpreter’s environment; virtual environments (python -m venv) keep each project’s dependencies separate.

The import system and reusing code

The import statement is the mechanism behind Python’s large ecosystem. Importing a module runs its top-level code once, binds its functions, classes and variables to a namespace, and caches the module so later imports are instant. For example:

import math
result = math.sqrt(25)   # 5.0

Here the standard-library math module is imported and its sqrt function is called through the module namespace. Beyond the standard library, community packages such as Flask, Django, TensorFlow and scikit-learn are installed with pip and imported exactly the same way. The if __name__ == "__main__": guard described above is what lets a single file be both imported as a module and run as a script without its top-level code firing twice.

Packaging a script into a standalone .exe

There is no format conversion from source code to a binary, so “py to exe” is not a converter. What people actually want is to bundle the script with a copy of the interpreter and its dependencies into one executable that runs on a machine without Python installed. The common tool is PyInstaller: pyinstaller --onefile file.py produces a single .exe. Alternatives are cx_Freeze and Nuitka (which compiles Python to C first). The result is larger than the original .py because it embeds the whole runtime, and it is platform-specific: a Windows build does not run on macOS. To put Python code on Android you do not convert the file either; you build an APK with a framework such as Kivy + Buildozer or BeeWare Briefcase that packages a Python runtime into the app.

Frequently asked questions

How do I run a .py file?

Install Python from python.org, open a terminal in the file’s folder, and type python file.py (Windows) or python3 file.py (macOS/Linux). Running from a terminal, rather than double-clicking, keeps the window open so you can read any error before it closes.

How do I open a .py file to read the code?

It is plain text, so any editor opens it. Use VS Code or Notepad++ for syntax highlighting; plain Notepad works but mangles Unix line endings. Reading it never executes anything.

What is the difference between .py and .pyc?

The .py is the human-readable source you edit; the .pyc is the compiled bytecode CPython caches in __pycache__ to start faster. Python regenerates the .pyc automatically, and it is tied to one interpreter version through the magic number in its header.

Why won’t my Python script run?

Usually one of three things: Python is not installed or not on PATH; the script targets Python 2 (EOL 2020) but you have Python 3, or the reverse, so print and other syntax break; or a library is missing, giving ModuleNotFoundError, which pip install fixes.

References