KAHIBARO Bookshelves
Discord Login Register

14.6. Practical automation examples

Small, Realistic Automation Scripts

In this chapter, you’ll see complete, realistic examples of automation you can build with just basic Python. Each example is small enough to understand, but useful enough that you could adapt it for your own life or work.

You don’t need to memorize these. Read them to get ideas, then adapt or copy-paste and modify them.

All scripts below assume you run them as Python files (for example: python my_script.py in a terminal).


1. Daily Log File Creator

Imagine you keep a daily notes file, like 2025-12-16-notes.txt. You can automate creating a new file with today’s date in the name.

This uses:

  • Dates from the datetime module
  • File creation and writing
  • Simple string formatting
from datetime import date
import os
def create_daily_log(folder="logs"):
    # Make sure the folder exists
    os.makedirs(folder, exist_ok=True)
    today = date.today()  # e.g. 2025-12-16
    filename = f"{today}-notes.txt"
    filepath = os.path.join(folder, filename)
    if os.path.exists(filepath):
        print(f"Log file already exists: {filepath}")
    else:
        with open(filepath, "w", encoding="utf-8") as f:
            f.write(f"Notes for {today}\n")
            f.write("=" * 30 + "\n\n")
        print(f"Created new log file: {filepath}")
if __name__ == "__main__":
    create_daily_log()

How you might use this:

  • Run it each morning to create a new notes file.
  • Add it to your system’s scheduler so it runs automatically every day.

Try changing:

  • The folder name from "logs" to something else
  • The initial text it writes into the file

2. Bulk File Renamer (Add Prefix or Suffix)

Renaming many files by hand is tedious. Let’s automate adding a prefix like OLD_ to all .txt files in a folder.

This uses:

  • Walking through files in a folder
  • Checking file extensions
  • Renaming files safely
import os
def add_prefix_to_txt_files(folder, prefix="OLD_"):
    for filename in os.listdir(folder):
        # Only process .txt files
        if filename.lower().endswith(".txt") and not filename.startswith(prefix):
            old_path = os.path.join(folder, filename)
            new_filename = prefix + filename
            new_path = os.path.join(folder, new_filename)
            print(f"Renaming {old_path} -> {new_path}")
            os.rename(old_path, new_path)
if __name__ == "__main__":
    # Change this to a folder you want to test with
    folder_path = "test_files"
    add_prefix_to_txt_files(folder_path, prefix="OLD_")

Things to try:

  • Change it to add a suffix instead, like _backup before the .txt.
  • Adjust it to work only on files that contain a certain word in the name.

Always test on a copy of your files first.


3. Simple Folder Cleaner (Move Files by Type)

You may have a “Downloads” folder full of different file types. Let’s sort them into subfolders like Images/, Documents/, etc.

This uses:

  • Checking file extensions
  • Moving files into subfolders
import os
import shutil
def organize_folder(folder):
    # Define categories by file extension
    categories = {
        "Images": [".png", ".jpg", ".jpeg", ".gif"],
        "Documents": [".pdf", ".docx", ".txt"],
        "Spreadsheets": [".xls", ".xlsx", ".csv"],
        "Archives": [".zip", ".rar", ".7z"],
    }
    for filename in os.listdir(folder):
        full_path = os.path.join(folder, filename)
        # Skip folders
        if not os.path.isfile(full_path):
            continue
        _, ext = os.path.splitext(filename)
        ext = ext.lower()
        moved = False
        for category, extensions in categories.items():
            if ext in extensions:
                category_folder = os.path.join(folder, category)
                os.makedirs(category_folder, exist_ok=True)
                new_path = os.path.join(category_folder, filename)
                print(f"Moving {full_path} -> {new_path}")
                shutil.move(full_path, new_path)
                moved = True
                break
        if not moved:
            print(f"Leaving {filename} (no matching category)")
if __name__ == "__main__":
    # Change this to a folder you want to organize
    folder_path = "Downloads"
    organize_folder(folder_path)

Ideas to customize:

  • Add more file extensions and categories.
  • Add a category like "Other" and move all uncategorized files there.

4. Find Text in Many Files

Suppose you have many .txt files and you want to find which ones contain a certain word or phrase. You can automate this search.

This uses:

  • Reading text files in a loop
  • Searching for substrings in text
import os
def search_in_text_files(folder, search_term):
    search_term_lower = search_term.lower()
    matches = []
    for filename in os.listdir(folder):
        if not filename.lower().endswith(".txt"):
            continue
        filepath = os.path.join(folder, filename)
        with open(filepath, "r", encoding="utf-8", errors="ignore") as f:
            content = f.read()
        if search_term_lower in content.lower():
            matches.append(filename)
    if matches:
        print(f'The term "{search_term}" was found in:')
        for name in matches:
            print(" -", name)
    else:
        print(f'No matches for "{search_term}" in {folder}')
if __name__ == "__main__":
    folder_path = "notes"
    term = input("Enter a word or phrase to search for: ")
    search_in_text_files(folder_path, term)

You can extend this to:

  • Count how many times a word appears in each file.
  • Show the lines where the term appears.

5. Simple CSV Report (Summing Numbers)

CSV files are common in spreadsheets and data. Let’s automate a basic report: sum a column of numbers from a CSV file.

Example CSV (expenses.csv):

date,category,amount
2025-01-01,Food,12.50
2025-01-01,Transport,3.20
2025-01-02,Food,8.75

The script:

import csv
def total_amount_from_csv(csv_file, column_name="amount"):
    total = 0.0
    with open(csv_file, "r", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        for row in reader:
            # Convert text to float
            value = float(row[column_name])
            total += value
    return total
if __name__ == "__main__":
    filename = "expenses.csv"
    result = total_amount_from_csv(filename, "amount")
    print(f"Total amount in {filename}: {result}")

Things to try:

  • Sum only certain categories (like only "Food").
  • Calculate both the total and the average.

6. Simple Reminder Script (Console)

You can use Python to remind you to take a break, drink water, or stand up. This simple version just prints reminders after a delay.

This uses:

  • Pausing with time.sleep()
  • A small loop
import time
def reminder_every(seconds, message, repetitions=5):
    print(f"Reminder started. I will remind you {repetitions} times.")
    for i in range(1, repetitions + 1):
        time.sleep(seconds)
        print(f"[Reminder {i}/{repetitions}] {message}")
if __name__ == "__main__":
    # Reminder every 10 seconds (change as needed)
    reminder_every(10, "Look away from the screen for a moment.", repetitions=3)

Ideas to improve:

  • Let the user choose the time interval and message.
  • Log reminders to a file (combine with the daily log idea).

7. Text-based To-Do List (File-backed)

Let’s make a very simple to-do list manager that stores tasks in a text file.

We’ll support:

  • Adding a task
  • Listing all tasks
  • Marking a task as done (by line number)

The tasks will be stored in todo.txt:

TODO_FILE = "todo.txt"
def show_tasks():
    try:
        with open(TODO_FILE, "r", encoding="utf-8") as f:
            lines = f.readlines()
    except FileNotFoundError:
        lines = []
    if not lines:
        print("No tasks yet!")
        return
    print("Your tasks:")
    for i, line in enumerate(lines, start=1):
        print(f"{i}. {line.strip()}")
def add_task(task_text):
    with open(TODO_FILE, "a", encoding="utf-8") as f:
        f.write(task_text + "\n")
    print("Task added.")
def mark_done(task_number):
    try:
        with open(TODO_FILE, "r", encoding="utf-8") as f:
            lines = f.readlines()
    except FileNotFoundError:
        print("No tasks to mark as done.")
        return
    if task_number < 1 or task_number > len(lines):
        print("Invalid task number.")
        return
    done_task = lines.pop(task_number - 1).strip()
    with open(TODO_FILE, "w", encoding="utf-8") as f:
        f.writelines(lines)
    print(f"Marked as done and removed: {done_task}")
def main():
    while True:
        print("\nTo-Do List Manager")
        print("1. Show tasks")
        print("2. Add task")
        print("3. Mark task as done")
        print("4. Quit")
        choice = input("Choose an option (1-4): ").strip()
        if choice == "1":
            show_tasks()
        elif choice == "2":
            task = input("Enter a new task: ").strip()
            if task:
                add_task(task)
        elif choice == "3":
            number = input("Enter task number to mark as done: ").strip()
            if number.isdigit():
                mark_done(int(number))
            else:
                print("Please enter a number.")
        elif choice == "4":
            print("Goodbye!")
            break
        else:
            print("Invalid choice. Please try again.")
if __name__ == "__main__":
    main()

This combines:

  • User input
  • File reading/writing
  • A simple menu loop

You could later turn this into a more advanced project with priorities or deadlines.


8. Turning a Manual Routine into a Script

When you want to automate something, a useful approach is:

  1. Write down the steps you do by hand.
  2. See which steps are repetitive and rule-based.
  3. Translate each step into Python operations.

Here’s a “template” function you can adapt:

def automate_my_task():
    # 1. Locate input files or data
    # 2. Read or load the data
    # 3. Process or transform the data
    # 4. Write results to a new file or folder
    # 5. Optionally: print a summary or log file
    pass

When you find yourself doing something boring and repetitive, ask:

  • “Could Python read these files instead of me?”
  • “Could Python rename/move these files automatically?”
  • “Could Python summarize these numbers/texts for me?”

Those questions often lead directly to your next automation script.

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