Advertisement
🤖 Real-World

Python Automation – Automate Repetitive Tasks

Python excels at automation. From renaming thousands of files to sending daily reports, Python scripts eliminate hours of manual work.

⏱️ 20 min read🎯 Real-World📅 Updated 2026

File Automation with pathlib

Python
from pathlib import Path
import shutil

downloads = Path.home() / "Downloads"
categories = {
    ".pdf": "Documents",
    ".jpg": "Images", ".jpeg": "Images", ".png": "Images",
    ".mp4": "Videos",
    ".zip": "Archives",
}

for file in downloads.iterdir():
    if file.is_file() and file.suffix.lower() in categories:
        dest_dir = downloads / categories[file.suffix.lower()]
        dest_dir.mkdir(exist_ok=True)
        shutil.move(str(file), dest_dir / file.name)
        print(f"Moved {file.name}")

Scheduling Tasks

Python
import schedule
import time

def daily_report():
    print("Generating report...")

schedule.every().day.at("09:00").do(daily_report)
schedule.every().hour.do(lambda: print("Heartbeat"))

while True:
    schedule.run_pending()
    time.sleep(60)

Sending Emails

Python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email(to, subject, body, smtp_pass):
    msg = MIMEMultipart()
    msg["From"] = "you@gmail.com"
    msg["To"] = to
    msg["Subject"] = subject
    msg.attach(MIMEText(body, "html"))
    with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
        server.login("you@gmail.com", smtp_pass)
        server.sendmail("you@gmail.com", to, msg.as_string())

Excel with openpyxl

Python
import openpyxl
from openpyxl.styles import Font, PatternFill

wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Report"

headers = ["Product", "Units", "Revenue"]
for col, h in enumerate(headers, 1):
    cell = ws.cell(row=1, column=col, value=h)
    cell.font = Font(bold=True)

data = [("Widget A", 150, 7500), ("Widget B", 230, 11500)]
for row_idx, row_data in enumerate(data, 2):
    for col_idx, value in enumerate(row_data, 1):
        ws.cell(row=row_idx, column=col_idx, value=value)

wb.save("report.xlsx")
Tip: Store credentials in a .env file and load with python-dotenv — never hardcode passwords in scripts.

Automation: Let Python Do the Boring Work

Automation is one of Python's most practical uses — replacing repetitive manual tasks (renaming files, sending reports, cleaning data) with a script you run once and reuse forever. The standard-library tools cover most needs.

TaskModule
files & folderspathlib, shutil
run other programssubprocess
schedulingOS cron / Task Scheduler
web/API tasksrequests
from pathlib import Path

# rename every .txt in a folder to .md
for file in Path("notes").glob("*.txt"):
    file.rename(file.with_suffix(".md"))

Use pathlib, not string paths: Path("a") / "b" / "c.txt" builds paths that work on every OS, with methods like .glob(), .exists(), and .rename() — far cleaner than fragile os.path.join string juggling. Golden rule of destructive automation: a script that renames, moves, or deletes files can wreck data fast — test on a copy first, print what it would do (a dry run) before actually doing it, and back up. Scheduling: to run a script automatically (nightly cleanup, hourly report), register it with your OS scheduler (cron on Linux/macOS, Task Scheduler on Windows) rather than leaving a Python loop running. Use subprocess.run([...], check=True) to invoke other command-line tools safely.

🏋️ Practical Exercise

Automate routine tasks:

  1. Use pathlib to list every .txt file in a folder.
  2. Rename or move files into subfolders based on their extension.
  3. Schedule a function to run every few seconds with the schedule library (or a loop with time.sleep).
  4. Write a script that appends a timestamped line to a log file each run.

🔥 Challenge Exercise

Write a “downloads organizer” that scans a folder and moves files into category subfolders (Images, Documents, Archives, Other) based on their extension, creating folders as needed and avoiding name collisions. Make it safe to run repeatedly. Bonus: schedule it to run periodically and email yourself a summary of how many files were moved.

📋 Summary

  • Python excels at automating repetitive file, data, and communication tasks.
  • pathlib offers a clean, object-oriented API for filesystem work.
  • Schedule recurring jobs with the schedule library, a loop, or OS tools like cron.
  • Libraries like openpyxl (Excel) and smtplib (email) extend automation reach.
  • Make scripts idempotent and add logging so reruns are safe and observable.
  • Wrap risky steps in error handling so failures are reported, not hidden.

Interview Questions on Automation

  • What kinds of tasks are good candidates for automation with Python?
  • Why is pathlib preferred over os.path for file work?
  • How do you schedule recurring tasks in Python?
  • What libraries help automate Excel or email?
  • How do you make an automation script safe to run repeatedly (idempotent)?
  • How do you handle errors so an automation does not silently fail?
  • What is the difference between scheduling in-process and using cron / Task Scheduler?

FAQ

Why use pathlib instead of os.path? +

pathlib represents paths as objects with intuitive methods and the / operator for joining (folder / "file.txt"). It is more readable and less error-prone than string-based os.path functions.

How do I run a script automatically on a schedule? +

For simple cases use the schedule library or a while loop with time.sleep. For reliable, system-level scheduling, use cron on Linux/macOS or Task Scheduler on Windows to run the script at set times.

How do I make an automation safe to re-run? +

Design it to be idempotent: check whether an action is already done before doing it (e.g. skip files already moved), avoid overwriting data unintentionally, and log each action so you can audit what happened.

Can Python automate Excel and email? +

Yes. Use openpyxl or pandas for Excel files, and smtplib with email for sending mail. For richer Office automation there are libraries like xlsxwriter and provider-specific email APIs.