Table of Contents
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
datetimemodule - 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
_backupbefore 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.75The 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:
- Write down the steps you do by hand.
- See which steps are repetitive and rule-based.
- 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
passWhen 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.