Intermediate   Chapter 179 · 35 min read · Module 14: Advanced Application Development

Introduction to Automation

Learning objectives
  • After this chapter you can explain what automation is and decide which tasks are worth automating.
  • You can rename, move and sort files with pathlib.
  • You can read and summarise CSV data and search text with regular expressions.
  • You can add retries and clear messages to make an automatic job reliable.
  • You can describe how scripts are scheduled to run by themselves.

Automation means letting the computer do work that a person would otherwise repeat by hand. Renaming two hundred photos, copying numbers from a report into a sheet, or checking a log file every morning are all jobs that waste human time and are easy to get wrong when you are tired. A short Python script does the same job in seconds and never gets bored.

Python is one of the best languages for this work. Its syntax is easy to read, its standard library already contains tools for files, text, dates, spreadsheets and the web, and thousands of extra packages are one install away. Many people who never plan to become developers learn Python only to automate their daily tasks.

In this chapter you will learn how to decide what to automate, and then you will practise on the most common jobs: working with files, reading tables, searching text and making a job safe to repeat. The examples are deterministic and use temporary folders, so they are safe to run anywhere.

What is worth automating?

Not every task needs a script. A good rule is to ask three questions. Is the task boring and repeated often? Are the steps clear and always the same? Does a mistake cost time or money? If the answers are yes, automation will pay back the hours you spend writing it. If you do a task once a year and it takes five minutes, doing it by hand is probably fine.

Automation: using a program to perform a task with little or no human effort each time it runs

Start small. Write a script that does the task exactly as you do it by hand, check that it works, and then improve it. Print clear messages while it runs so that you can see what is happening. Many failed automation projects start too big and become hard to trust.

Automating files and folders

The pathlib module treats paths as objects. A Path can join parts with the / operator, list a folder with iterdir(), search with glob() and rglob(), create a folder with mkdir(), and move a file with rename(). Properties such as name, suffix and stem give you pieces of the file name, which makes sorting by file type easy.

Example 1: Sort files into folders by type
from pathlib import Path
import tempfile

with tempfile.TemporaryDirectory() as folder:
    root = Path(folder)
    for name in ["notes.txt", "photo.jpg", "todo.txt", "song.mp3", "logo.jpg"]:
        (root / name).write_text("data")

    for file in sorted(root.iterdir()):
        target = root / file.suffix.lstrip(".")
        target.mkdir(exist_ok=True)
        file.rename(target / file.name)

    for file in sorted(root.rglob("*")):
        if file.is_file():
            print(file.relative_to(root).as_posix())
jpg/logo.jpg jpg/photo.jpg mp3/song.mp3 txt/notes.txt txt/todo.txt
The script above uses a temporary folder so that it cannot touch your own files. When you automate with real files, test on a copy first, because renaming and deleting cannot always be undone.

Automating spreadsheets and data

The csv module reads and writes comma separated files that Excel and other tools can open. DictReader turns each row into a dictionary with the column names as keys, so you can write row["score"] and your code stays readable. Remember that every value arrives as text, so convert numbers with int() or float() before doing arithmetic. For Excel files with formulas and formats you can install a package such as openpyxl, and for large tables the pandas library is the usual choice.

Example 2: Summarise a CSV table
import csv
import io

raw = """name,score
Asha,82
Ben,67
Cara,91
"""
rows = list(csv.DictReader(io.StringIO(raw)))
total = sum(int(r["score"]) for r in rows)
best = max(rows, key=lambda r: int(r["score"]))
print("Students:", len(rows))
print("Average:", round(total / len(rows), 1))
print("Top:", best["name"])
Students: 3 Average: 80.0 Top: Cara

Automating text work

Logs, emails and reports are full of text that follows a pattern. Regular expressions from the re module let you describe a pattern and then find or replace every match. In the next example, we pull every error line out of a small log and count them. Watching a log and acting on a certain word is a very common job in operations and support.

Example 3: Find error lines in a log
import re

log = """2024-05-01 INFO start
2024-05-01 ERROR disk full
2024-05-02 INFO retry
2024-05-02 ERROR timeout
"""
errors = re.findall(r"^(\S+) ERROR (.+)$", log, flags=re.MULTILINE)
for day, message in errors:
    print(f"{day}: {message}")
print("Error count:", len(errors))
2024-05-01: disk full 2024-05-02: timeout Error count: 2

Making jobs reliable

A script that runs when nobody is watching must handle problems on its own. Networks drop, files are locked and servers are busy. Use try and except around steps that can fail, and retry a few times with a short pause. Always write a message about what failed, and stop with a clear result instead of looping forever. Good scripts are also idempotent, which means running them twice gives the same final result as running them once.

Example 4: Retry a flaky step
import time

def retry(task, attempts=3, wait=0):
    for number in range(1, attempts + 1):
        try:
            return task(number)
        except ValueError as error:
            print(f"Attempt {number} failed: {error}")
            time.sleep(wait)
    return "gave up"

def flaky(number):
    if number < 3:
        raise ValueError("not ready")
    return "done"

print(retry(flaky))
Attempt 1 failed: not ready Attempt 2 failed: not ready done

Running jobs on a schedule

A script becomes real automation when it runs by itself. On Linux and macOS the tool cron starts programs at set times, and on Windows the Task Scheduler does the same job. Inside Python you can use a package such as schedule, or the standard library sched and threading.Timer, but a loop like this only works while the program stays running. For important work, prefer the scheduler of the operating system or a cloud service because it also restarts after the machine reboots.

Example 5: A scheduled backup loop
import time
import schedule  # pip install schedule

def backup():
    print("Backing up files...")

schedule.every().day.at("02:00").do(backup)

while True:
    schedule.run_pending()
    time.sleep(30)
(waits and prints "Backing up files..." every day at 02:00)

Other useful tools for automation are shutil for copying and zipping folders, subprocess for running other programs, smtplib and email for sending mail, requests for web services, and logging to write a record of what the script did.

Python syntax

Syntax
from pathlib import Path
for f in Path(".").glob("*.txt"):
    print(f.name)
Syntax
import csv
with open("data.csv", newline="") as f:
    for row in csv.DictReader(f):
        print(row["column"])
Syntax
import shutil
shutil.copy("a.txt", "backup/a.txt")

Real-world applications

  • Sorting and renaming downloaded files
  • Creating weekly reports from spreadsheets
  • Sending reminder emails from a list
  • Collecting data from websites and APIs
  • Cleaning and converting data files before analysis

Common mistakes

Mistake: Testing a delete or rename script on real files
Fix: Test on a copy or a temporary folder and print what will happen before you do it.
Mistake: Treating CSV values as numbers when they are text
Fix: Convert with int() or float() before calculating.
Mistake: Hard coding absolute paths like C:\Users\me\file.txt
Fix: Use pathlib and relative paths or take the path as an argument.
Mistake: Catching every error with a bare except and hiding problems
Fix: Catch specific errors and print or log the message.
Mistake: Writing an infinite loop with no sleep, which uses all the CPU
Fix: Add time.sleep or use a scheduler.

Important tips

  • Automate the smallest useful piece first.
  • Add a dry run option that only prints what would change.
  • Use the logging module so you can check what happened later.
  • Keep passwords out of scripts and read them from environment variables.
  • Estimate the time saved before you start writing.

Key points summary

  • Automation is for tasks that are repeated, clear and boring.
  • pathlib handles files and folders in a portable way.
  • csv.DictReader makes table rows easy to read.
  • Regular expressions find patterns in text.
  • Retries and clear messages make scripts reliable.
  • Use cron or Task Scheduler to run scripts on a timetable.

Exam and interview points

  • Automation reduces manual, repetitive effort.
  • pathlib.Path offers glob, rglob, mkdir and rename.
  • csv.DictReader gives each row as a dictionary of strings.
  • An idempotent script gives the same result when run again.
  • cron and Task Scheduler start scripts at set times.

Quick revision

  • Automate tasks that are frequent, clear and risky by hand.
  • Path(...).glob("*.txt") finds files.
  • csv values are strings.
  • re.findall returns all matches.
  • try/except plus retry makes a job robust.
  • Schedule with cron or Task Scheduler.

Frequently asked questions

Do I need to be an expert to automate tasks?

No. Basic knowledge of files, loops, functions and a few standard modules is enough for most useful scripts.

How do I know a task is worth automating?

Compare the time to write the script with the time you will save over a year. Also count the cost of mistakes.

Is it safe to automate deleting files?

Only with care. Do a dry run, test on copies, and consider moving files to a trash folder instead of deleting them.

Can Python automate programs that have no API?

Sometimes. Libraries such as pyautogui can click and type, but they are fragile. Use an official API or file export when possible.

How can I run a script every day?

Use cron on Linux or macOS, Task Scheduler on Windows, or a cloud scheduler. Make sure the script uses full paths or sets its own working folder.

Practise this chapter

21 practice questions Take the chapter quiz

Related chapters