Python Source Files and Scripts

Learn what Python source files are, how .py files work, and the difference between running a script and importing a module.

5 min read

Every Python program you write starts as a text file with a .py extension. This file is called a source file, and it contains Python statements that the interpreter reads and executes. Up until now, you have probably been typing code into the interactive interpreter or running single files with a few lines. As your programs grow, understanding how source files work as both scripts and modules becomes essential for organizing your code.

A single .py file can serve two different roles depending on how you use it. When you pass it to the Python interpreter as a command-line argument, it runs as a script: Python executes every statement from top to bottom and then exits. When you use the import statement to load it from another file, it acts as a module: Python executes the file once to define its functions and variables, then makes those definitions available to the importing code. The same file can handle both roles gracefully with a simple built-in pattern.

Running a file as a script

The simplest way to execute Python code is to put it in a file and run it with the python command. You create a file, give it a name ending in .py, write your statements, and then run it from the terminal. Python reads the file, compiles it to bytecode, and executes the statements in order from top to bottom. When the last statement finishes, the program exits.

Here is a small script that prints a greeting and a calculation:

pythonpython
name = "Maya"
score = 95
print("Hello, " + name)
print("Your score is", score)

Save these lines in a file called greet.py and run it with python greet.py. Python executes the three statements in sequence and shows the output. The file does not need any special header or boilerplate. Every top-level statement in the file runs exactly once, in the order it appears.

Using a file as a module

The same .py file can also be loaded by another Python file using the import statement. When you import a file, Python executes it once to define its contents, then makes those definitions available through the module name. This is how you reuse functions and variables across multiple files without copying and pasting code.

When Python imports a file, it sets a special built-in variable called name to the name of the module. When you run a file directly as a script, Python sets name to the string 'main' instead. This difference lets you write code that behaves one way when run as a script and another way when imported as a module. The standard pattern looks like this:

pythonpython
def greet(name):
    print("Hello, " + name)
 
if __name__ == "__main__":
    greet("Maya")

When this file runs as a script, name equals 'main', the condition is true, and greet is called. When another file imports this one, name equals the module name, the condition is false, and only the function definition is executed. The greet function becomes available to the importer, but the call at the bottom does not run. This pattern is used in nearly every Python file that is designed to be both reusable and runnable.

How Python finds your files

When you import a module, Python searches for it in a specific order. First, it checks if the name belongs to a built-in module compiled into the interpreter. If not, it searches for a .py file with the matching name in a list of directories stored in sys.path. This list starts with the directory containing the script you ran, followed by directories listed in the PYTHONPATH environment variable, and finally the standard library and site-packages directories where third-party packages are installed.

For simple projects where all your .py files are in the same directory, importing just works. When you start organizing code into subdirectories and packages, you will need to understand the search path in more detail. For now, keeping all your source files in one folder is the simplest way to practice importing and reusing code. If you have read about Python identifiers and naming rules, you already know how to name your .py files correctly: use lowercase letters, underscores for spaces, and avoid names that clash with Python keywords or standard library modules.

A mental model for source files

Think of each .py file as having two possible identities. As a script, it is the entry point of a program: it runs once, does its job, and exits. As a module, it is a library of definitions: it runs once to set up its contents, then waits to be used by other code. The name check is the switch that lets a file know which identity it is using.

This dual nature is what makes Python projects scalable. You start with a single script in a single file. When it grows too large, you extract reusable functions into separate files and import them back. Those files can later be organized into packages and distributed as libraries. The journey from a one-file script to a multi-file project is natural in Python, and it all starts with understanding how source files work. If you are ready to see these concepts combined into a complete working program, the article on building your first Python console program ties everything together.

Rune AI

Rune AI

Key Insights

  • Python source files end in .py and contain statements that execute from top to bottom.
  • Running a file as a script sets name to 'main'; importing sets it to the module name.
  • The if name == 'main' pattern lets a file work as both a script and an importable module.
  • Python searches for modules using sys.path, starting with the current directory.
RunePowered by Rune AI

Frequently Asked Questions

What is the difference between running a Python file and importing it?

When you run a file with python myfile.py, Python sets the __name__ variable to '__main__' and executes all top-level code. When you import it, Python sets __name__ to the module name and executes the file once to define its contents. The same file can work both ways.

Can I run a Python script without the .py extension?

On Unix-like systems, you can add a shebang line (#!/usr/bin/env python3) at the top and make the file executable with chmod +x. On Windows, .py files are associated with the Python interpreter by default.

Why does Python create a __pycache__ folder?

Python caches compiled bytecode in __pycache__ to speed up future imports. The .pyc files are created automatically and can be safely ignored or deleted. Python regenerates them as needed.

Conclusion

Every Python program you write lives in a .py file. Running a file as a script executes its code from top to bottom. Importing a file as a module loads its definitions once and makes them available for reuse. Understanding this dual nature of source files is the foundation for organizing larger programs across multiple files and eventually building your own modules and packages.