Table of Contents
Why Start with Simple Automation?
Simple automation tasks are small, everyday problems you can solve with short Python scripts. They are:
- Quick to write
- Immediately useful
- Great practice for combining basics: variables, conditions, loops, functions, and files
In this chapter, you’ll see patterns you can reuse again and again for small automations, such as:
- Renaming or sorting files
- Cleaning up text
- Doing repetitive calculations
- Sending yourself information
You do not need advanced Python to automate simple tasks—only what you already know from earlier chapters.
Typical Simple Automation Patterns
Most simple automations follow a similar flow:
- Get input
From the user, a file, or the environment (e.g., current date/time, folder contents). - Process data
Clean, filter, format, compute, or transform something. - Produce output
Print results, write to a file, rename a file, or show a summary.
You can think of it as:
$$\text{input} \rightarrow \text{processing} \rightarrow \text{output}$$
Let’s look at common patterns and examples.
Automating Repetitive Calculations
If you find yourself using a calculator the same way every day, you can write a script once and reuse it.
Example: Monthly Salary Calculator
Suppose you often calculate your monthly pay from hourly wage and hours worked.
hourly_rate = float(input("Hourly rate: "))
hours_per_week = float(input("Hours per week: "))
weeks_per_month = 4.33 # average
monthly_pay = hourly_rate * hours_per_week * weeks_per_month
print("Estimated monthly pay:", round(monthly_pay, 2))This script:
- Asks for inputs once
- Applies the same formula every time
- Gives a consistent, quick result
You can adapt this pattern for:
- Tax or discount calculators
- Loan or interest estimators
- Converting currencies or units (e.g., km to miles)
Example: Batch Conversion with a Loop
If you need to convert many values:
print("Enter prices in euros, one per line. Enter 0 to finish.")
rate = float(input("Euro to dollar rate: "))
while True:
euro = float(input("Price in euros (0 to stop): "))
if euro == 0:
break
dollars = euro * rate
print("In dollars:", round(dollars, 2))Pattern:
- Loop
- Stop condition (
0to finish) - Reuse of the same calculation
Automating Text-Based Tasks
Many everyday tasks involve text: cleaning, formatting, or extracting information.
Basic Text Cleanup
Imagine you often receive a list of items with messy spacing and uppercase/lowercase differences. You want a clean, numbered list.
raw_items = input("Enter items separated by commas: ")
items = raw_items.split(",") # split into a list
clean_items = []
for item in items:
item = item.strip() # remove leading/trailing spaces
item = item.capitalize() # make first letter uppercase
clean_items.append(item)
print("\nClean list:")
for i, item in enumerate(clean_items, start=1):
print(i, "-", item)This automates:
- Splitting text into pieces
- Cleaning each piece
- Outputting a readable list
You can adapt this to:
- Normalize names (e.g.,
"john doe"→"John Doe") - Clean email lists
- Prepare data for another program
Simple Text Replacement Script
If you repeatedly need to replace certain words or phrases in a block of text, you can automate it.
text = input("Enter some text:\n")
old = input("Text to replace: ")
new = input("Replace with: ")
updated = text.replace(old, new)
print("\nUpdated text:")
print(updated)Use this for:
- Fixing repeated typos
- Updating product names
- Changing placeholders in templates
Automating with Files and Folders (Lightweight)
You already know basics of working with files. Simple automation often combines those basics with loops and conditions.
Example: Reading a File and Making a Summary
Suppose you have a text file tasks.txt, one task per line, and you want to count how many tasks there are.
filename = "tasks.txt"
# Count non-empty lines as tasks
count = 0
with open(filename, "r", encoding="utf-8") as f:
for line in f:
if line.strip(): # skip empty lines
count += 1
print("You have", count, "tasks in", filename)You can adapt this to:
- Count lines containing a word (e.g.,
"ERROR") - Count how many items match a condition (e.g., “completed”)
Example: Creating a Simple Log File
Automation scripts often write logs—simple text files that record what happened and when.
from datetime import datetime
message = input("What happened? ")
now = datetime.now()
timestamp = now.strftime("%Y-%m-%d %H:%M:%S")
with open("log.txt", "a", encoding="utf-8") as f:
f.write(f"[{timestamp}] {message}\n")
print("Event logged.")This script:
- Takes a quick note
- Adds a timestamp
- Appends it to
log.txt
Use it as a tiny journaling or tracking tool (e.g., study sessions, workout notes).
Simple File-Based Helper Tools
Small scripts can act as “helpers” for file-related tasks you often do manually.
Example: Add Line Numbers to a File
You have a file notes.txt and want a numbered version notes_numbered.txt.
input_file = "notes.txt"
output_file = "notes_numbered.txt"
with open(input_file, "r", encoding="utf-8") as fin, \
open(output_file, "w", encoding="utf-8") as fout:
for i, line in enumerate(fin, start=1):
fout.write(f"{i}: {line}")
print("Numbered file saved as", output_file)This automates:
- Reading input file line by line
- Transforming each line
- Writing to a new file
Example: Simple Backup of a Text File
You can create quick backups by copying a file with a different name.
import os
from datetime import datetime
filename = "data.txt"
if os.path.exists(filename):
now = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_name = f"backup_{now}_{filename}"
with open(filename, "r", encoding="utf-8") as original, \
open(backup_name, "w", encoding="utf-8") as backup:
backup.write(original.read())
print("Backup created:", backup_name)
else:
print("File not found:", filename)This adds simple safety to any text-based work you do.
Tiny Personal Tools (Interactive Scripts)
Many simple automations are just small command-line tools that ask a question, then do something helpful.
Example: Quick To-Do Adder
Adds a new task to a plain text file.
task = input("New task: ")
with open("todo.txt", "a", encoding="utf-8") as f:
f.write("- " + task + "\n")
print("Task added to todo.txt")You can run this script quickly whenever you want to add a task, instead of opening a text editor.
Example: Simple Reminder Text Generator
Generates a reminder message you can copy-paste.
name = input("Person's name: ")
task = input("What should they remember? ")
time = input("When? (e.g., tomorrow, at 5pm): ")
message = f"Hi {name}, just a reminder about: {task}, {time}."
print("\nYour reminder message:")
print(message)You could extend this later to send an email or notification, but even just generating the text saves time and keeps messages consistent.
Combining Simple Tasks into a Workflow
Once you have several tiny scripts, you can start chaining them:
- Script A: cleans input data
- Script B: analyzes or transforms it
- Script C: formats or exports the results
For example, a basic workflow could be:
- Copy raw data into
raw.txt. - Run a script that cleans and saves
cleaned.txt. - Run a script that counts lines and saves a summary
summary.txt.
Each script stays small and focused, but together they automate a bigger job.
Finding Ideas for Simple Automations
Look for tasks that are:
- Repetitive: You do them often.
- Rule-based: Steps are clear and predictable.
- Text/number/file based: Easy for Python to handle.
Common ideas:
- Renaming files in a simple pattern (e.g.,
photo1.jpg,photo2.jpg, …) - Extracting certain lines from a log file
- Generating boilerplate text (email templates, reports, notes)
- Calculating totals or averages from a list of numbers
Whenever you think “I’ve done this 3 times already,” that’s a good candidate for a simple automation script.
Good Habits for Simple Automation Scripts
Even for small scripts, a few habits make them much more useful:
- Use clear names:
input_file,rate,tasksinstead ofx,a,stuff. - Add a short comment at the top describing what the script does.
- Validate input lightly when needed (e.g., check file exists, avoid division by zero).
- Test with small example data before using on important files.
These habits help you build reliable, reusable tools—even when they are only a few lines long.