KAHIBARO Bookshelves
Discord Login Register

14.2. Automating simple tasks

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:

  1. Get input
    From the user, a file, or the environment (e.g., current date/time, folder contents).
  2. Process data
    Clean, filter, format, compute, or transform something.
  3. 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 (0 to 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:

  1. Copy raw data into raw.txt.
  2. Run a script that cleans and saves cleaned.txt.
  3. 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, tasks instead of x, 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.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms