Chapter 17: Practical Python Examples
By now, you have learned the core of the Python language, its flow control structures, data types, functions, and the way it organises code into modules and packages. You have also explored some of the standard library and learned how Python can read, process, and transform data. In this chapter, we move from the conceptual to the practical.
Python is at its most powerful when applied to real problems. Whether you are automating routine tasks, analysing text, or building simple command-line tools, Python’s clarity and flexibility make it an excellent choice for small scripts and prototypes that often grow into robust tools.
This chapter presents a few complete examples that show how the pieces you have learned fit together. These examples are designed to be instructive rather than exhaustive. They combine standard library features with good coding practices to demonstrate how short, readable programs can achieve useful results.
We will begin with automation scripts that handle files and logs, move on to a simple text analysis and reporting example, and finish with a small command-line utility built with argparse. Each section builds confidence in applying Python to practical, everyday programming tasks.
Script Automation Example
One of Python’s most common uses is automating repetitive or manual tasks. File renaming, directory cleanup, and log processing are all classic examples where a few lines of Python can save hours of tedious work.
In this section we will create a short script that scans a folder, renames files according to a consistent pattern, and writes a simple log of the changes it made. The same principles can then be adapted for many other automation tasks.
# file_renamer.py
import os
from datetime import datetime
# Folder to process
folder = "C:/example/files"
# Generate a timestamp for the log
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
logfile = f"rename_log_{timestamp}.txt"
with open(logfile, "w", encoding="utf-8") as log:
for name in os.listdir(folder):
if name.endswith(".txt"):
new_name = name.lower().replace(" ", "_")
old_path = os.path.join(folder, name)
new_path = os.path.join(folder, new_name)
os.rename(old_path, new_path)
log.write(f"Renamed: {name} → {new_name}\n")
print("Renaming complete. Log written to", logfile)
This script performs a few important tasks:
- Iterates over all files in a given folder using
os.listdir(). - Applies a renaming rule (in this case, converting names to lowercase and replacing spaces with underscores).
- Writes a log file containing a timestamp and a record of each rename.
Automation scripts like this illustrate how Python can interact directly with the filesystem, combining readability and power in a way that encourages experimentation and refinement. Once a script has been tested, it can be scheduled or integrated into larger workflows with minimal effort.
Simple Text Analysis or Report Generator
Python’s strong support for string handling makes it ideal for analysing or summarising text data. Whether you are reviewing logs, generating reports, or scanning through documents, you can use a few built-in tools to extract meaning from plain text.
In this example, we will build a small program that reads a text file, counts the most common words, and produces a short summary report. This kind of script is useful for quick data exploration, keyword analysis, or preparing a summary of large text files.
# text_report.py
from collections import Counter
import re
# Read text from file
with open("sample.txt", "r", encoding="utf-8") as f:
text = f.read().lower()
# Split into words using a simple regex
words = re.findall(r"\b[a-z']+\b", text)
# Count the most common words
counter = Counter(words)
total_words = sum(counter.values())
# Write a short report
with open("report.txt", "w", encoding="utf-8") as out:
out.write("Word Frequency Report\n")
out.write("=====================\n\n")
out.write(f"Total words: {total_words}\n\n")
out.write("Top 10 words:\n")
for word, count in counter.most_common(10):
out.write(f"{word:>10}: {count}\n")
print("Report saved as report.txt")
The program combines a few powerful tools:
re.findall()to extract words from text using a regular expression.Counterfromcollectionsto count frequencies quickly and clearly.- File I/O to produce a readable text report that can be viewed or shared.
This kind of lightweight analysis is often enough to gain insight from unstructured data without relying on external tools. It also highlights Python’s advantage in turning simple ideas into practical, repeatable scripts.
Small Command-Line Utility (using argparse)
Many Python scripts become more useful when they can be run from the command line with arguments. Rather than editing code each time, you can supply options or file names when executing the script. The argparse module from the standard library makes this simple and consistent.
In this example, we will build a small utility that reads a text file and counts lines, words, and characters, similar to the Unix wc (word count) command. It will take an input file name as a required argument, and an optional flag to display detailed output.
# count_tool.py
import argparse
def count_text(path, verbose=False):
with open(path, "r", encoding="utf-8") as f:
text = f.read()
lines = text.splitlines()
words = text.split()
chars = len(text)
if verbose:
print(f"File: {path}")
print(f"Lines: {len(lines)}")
print(f"Words: {len(words)}")
print(f"Characters: {chars}")
return len(lines), len(words), chars
def main():
parser = argparse.ArgumentParser(
description="Count lines, words, and characters in a text file."
)
parser.add_argument("file", help="Path to the text file")
parser.add_argument(
"-v", "--verbose",
action="store_true",
help="Show detailed output"
)
args = parser.parse_args()
lines, words, chars = count_text(args.file, args.verbose)
if not args.verbose:
print(lines, words, chars)
if __name__ == "__main__":
main()
This small tool can be used directly from the terminal. For example:
python count_tool.py sample.txt
or, for more detail:
python count_tool.py sample.txt --verbose
#!/usr/bin/env python3 line at the top on Unix-like systems and make the file executable. This allows users to run the script directly.
The argparse module provides automatic help messages, type checking, and sensible error handling. It also scales well — you can add subcommands, default values, or configuration files later without changing how users run your script.
With this final example, you have seen how Python can automate tasks, analyse data, and provide user-friendly command-line interfaces. Each of these skills builds toward writing maintainable, useful programs that fit naturally into real-world work.