Coding

How to Write a Simple Python Script (Step by Step)

To write a simple Python script, put your code in a text file that ends in .py, then run it with python script.py (or py script.py on Windows). The script below counts the words in a text file you name on the command line, and it shows the structure most small scripts follow.

This page assumes Python 3 is installed. If the python command is missing, see how to install Python on Windows. If you have never run a file before, Hello World in Python covers the one-line version first.

The complete script

Create a file called wordcount.py and paste this in. It uses only the standard library, so there is nothing to install.

import argparse
import sys
from pathlib import Path


def count_words(path: Path) -> int:
    """Return the number of whitespace-separated words in a text file."""
    text = path.read_text(encoding="utf-8")
    return len(text.split())


def main() -> int:
    parser = argparse.ArgumentParser(description="Count the words in a text file.")
    parser.add_argument("filename", type=Path, help="text file to read")
    parser.add_argument("-v", "--verbose", action="store_true", help="print the file name too")
    args = parser.parse_args()

    if not args.filename.is_file():
        print(f"error: {args.filename} is not a file", file=sys.stderr)
        return 1

    total = count_words(args.filename)
    if args.verbose:
        print(f"{args.filename}: {total} words")
    else:
        print(total)
    return 0


if __name__ == "__main__":
    sys.exit(main())

Make a small test file next to it, notes.txt, containing the text The quick brown fox jumps over the lazy dog. Then run:

python wordcount.py notes.txt -v

Example output:

notes.txt: 9 words

Without -v the script prints only 9. The rest of this page explains each part, so you can change it into your own script.

Step 1: create the file

A Python script is a plain text file. Any editor works: Notepad, Visual Studio Code, or anything else that saves plain text. Save it with the .py extension and use a name without spaces, such as wordcount.py. Do not name it after a standard library module (argparse.py, pathlib.py or random.py): Python would import your file instead of the real module, and you would get confusing errors.

On Windows, check that the editor did not save wordcount.py.txt. Explorer hides known extensions by default, so the wrong name can look correct.

Step 2: import what you need

The first three lines bring in standard library modules:

  • argparse reads and validates command-line arguments.
  • sys gives access to the error stream (sys.stderr) and to sys.exit.
  • pathlib.Path represents file paths as objects, with methods for reading them.

Put imports at the top of the file, one per line. Importing only what you use keeps the file readable.

Step 3: write the logic as a function

The work happens in count_words. It takes a Path and returns an integer. Path.read_text() returns the decoded contents of the file as a string. According to the pathlib docs, the file is opened and then closed, and its optional parameters mean the same as in open(). The script passes encoding="utf-8" so that it reads the same way on every system and does not depend on the machine's default.

text.split() with no argument splits on any run of whitespace, so spaces, tabs and newlines all separate words, and len() counts the pieces. An empty file gives 0.

Keeping the logic in a function that takes input and returns a result, instead of printing inside it, makes it easy to test and reuse. You can call it from another script or from the interactive interpreter. For the syntax, see defining a function in Python if that article is new to you, or the official tutorial.

Step 4: read arguments from the command line

Hard-coding a file name into a script means editing the script for every new file. The argparse module avoids that. The docs' basic example has the same shape as this script:

  • add_argument("filename") creates a positional argument, because the name has no - prefix. It is required.
  • type=Path converts the text the user typed into a Path object.
  • action="store_true" makes -v/--verbose an on/off flag. It stores True when present and False when absent.
  • parse_args() reads sys.argv and returns a namespace. Each argument is an attribute: args.filename and args.verbose.

You also get a help screen for free. Run python wordcount.py -h and argparse prints a usage line, the description and a description of each argument. Example output:

usage: wordcount.py [-h] [-v] filename

Count the words in a text file.

positional arguments:
  filename       text file to read

options:
  -h, --help     show this help message and exit
  -v, --verbose  print the file name too

If you forget the file name, argparse stops the script itself. Per the docs, it prints the usage line and an error to sys.stderr, and the program exits with status code 2. Example output:

usage: wordcount.py [-h] [-v] filename
wordcount.py: error: the following arguments are required: filename

Step 5: handle the failure you expect

A user can type a file name that does not exist. Without a check, read_text() raises FileNotFoundError and Python prints a traceback. The script checks args.filename.is_file() first, prints a one-line message to sys.stderr with file=sys.stderr, and returns 1. Errors go to the error stream so that they do not mix with the normal output if someone redirects it to a file.

The check covers the common mistake and nothing else. A file that exists but is not valid UTF-8 would still raise UnicodeDecodeError. Catch only the errors you know how to handle. For the pattern, see Python exception handling with try and except.

Step 6: the main() pattern

The last two lines are the usual way to start a script:

if __name__ == "__main__":
    sys.exit(main())

The Python docs explain the idea. When a module is imported, __name__ is set to the module's name. When the file is executed as the top-level program, for example with python wordcount.py, __name__ is set to the string '__main__'. The block therefore runs only when you run the file directly. If another file does import wordcount, the functions are defined but nothing runs.

The docs also recommend putting as few statements as possible in that block, and usually wrapping the program's main behavior in a function named main. They note that main should return an integer or None, because sys.exit(main()) turns the return value into the process exit status. Returning 0 means success, and a non-zero value means failure, which matters when another program or a batch file checks whether your script worked.

Step 7: run it

Open a terminal in the folder that holds the script. The command that starts Python depends on the system:

SystemCommand
Windowspy wordcount.py notes.txt or python wordcount.py notes.txt
macOSpython3 wordcount.py notes.txt
Linuxpython3 wordcount.py notes.txt

You can also run the file from an editor. Running Python scripts in VS Code shows how to do it with a button instead of the terminal. Either way, the script and its output are the same.

Common errors and fixes

python is not recognized, or the Microsoft Store opens

On Windows, try py wordcount.py first. The py launcher finds an installed Python even when the python command is not set up. On macOS and Linux, use python3.

can't open file ... No such file or directory

Python reports that it cannot open the script when your terminal is in a different folder from the file. Use cd to go to the folder, or give the full path to the script. This is a different error from the script's own message about a missing text file. The first is about wordcount.py, and the second is about notes.txt.

SyntaxError or IndentationError

Python marks blocks with indentation, not braces. Every line inside a function or an if must be indented by the same amount, usually four spaces, and a line that ends with a colon needs an indented block under it. Do not mix tabs and spaces. See IndentationError: unexpected indent for the fixes.

Nothing happens when you run the script

If the script defines main() but the last two lines are missing, Python defines the functions and then exits without calling anything. Check that the if __name__ == "__main__": block is present and that it is not indented under another block.

Adapt the script to your own task

Keep the same skeleton and change the middle:

  • Replace count_words with your own function. Keep it free of print calls and return a value.
  • Add or remove arguments in main. A name that starts with - or -- is optional. A name without a dash is required.
  • To work on a whole folder, Path.glob("*.txt") yields the matching files in a directory, and rglob does the same recursively. The docs say the results come in no particular order, so wrap them in sorted() when the order matters.
  • To read a file one line at a time instead of all at once, see reading a file line by line in Python. That is the better choice for very large files.

Once your script needs third-party packages, install them in a virtual environment for that project, not into the system Python.

Frequently asked questions

What file extension does a Python script use?
A Python script is a plain text file that ends in .py. You run it by giving its name to the interpreter, for example python wordcount.py. The extension is a convention, but editors, the Windows py launcher and most tools expect it.
Do I need if __name__ == "__main__" in a simple script?
No, a script runs without it. The Python docs describe it as the way to run code only when the file is executed directly and not when another file imports it. It costs two lines and makes the file safe to import later, so it is a good habit.
How do I make my script accept input from the command line?
Use the argparse module from the standard library. Create an ArgumentParser, add the arguments with add_argument, and call parse_args. Python reads sys.argv for you, validates it and prints a usage message when an argument is missing.
Do I need to install anything besides Python?
No. A script like the one on this page uses only the standard library (argparse, pathlib and sys), so there is nothing to install with pip. You only need a virtual environment once you add third-party packages.

Sources