Follow AiTechWorlds on LinkedIn for professional AI content!Follow Now →

Python Automation: 20 Scripts That Will Save You Hours Every Week

20 ready-to-use Python automation scripts for 2025: file management, email automation, web scraping, system tasks, and API integrations that eliminate repetitive work.

A
AiTechWorlds Team
May 27, 2026 9 min read
📱

Get more content like this on Telegram!

Daily AI tips, notes & resources — free

Join Free →

Python Automation: 20 Scripts That Will Save You Hours Every Week

The moment Python automation clicked for me was a Thursday afternoon when I realized I'd been manually renaming 200 files every week for six months. The task took about 45 minutes. The Python script took 20 minutes to write, runs in 3 seconds, and I've never thought about that task again.

That's the automation mindset: the second time you do something repetitive on a computer, you should start thinking "could Python do this for me?"

Here are 20 scripts across different automation categories. Some are copy-paste ready; others are blueprints to adapt to your specific situation.


Category 1: File and Folder Automation

Script 1: Organize Downloads Folder by File Type

import shutil
from pathlib import Path

def organize_downloads():
    downloads = Path.home() / "Downloads"
    
    categories = {
        "Images": [".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg"],
        "Documents": [".pdf", ".docx", ".doc", ".txt", ".xlsx", ".csv"],
        "Videos": [".mp4", ".mov", ".avi", ".mkv"],
        "Archives": [".zip", ".tar", ".gz", ".rar"],
        "Code": [".py", ".js", ".html", ".css", ".json"],
    }
    
    moved = 0
    for file in downloads.iterdir():
        if file.is_file():
            for folder, extensions in categories.items():
                if file.suffix.lower() in extensions:
                    target = downloads / folder
                    target.mkdir(exist_ok=True)
                    shutil.move(str(file), target / file.name)
                    moved += 1
                    break
    
    print(f"Organized {moved} files.")

organize_downloads()

Script 2: Bulk Rename Files

from pathlib import Path

def bulk_rename(folder: str, old_pattern: str, new_pattern: str):
    path = Path(folder)
    renamed = 0
    for file in path.iterdir():
        if old_pattern in file.name:
            new_name = file.name.replace(old_pattern, new_pattern)
            file.rename(file.parent / new_name)
            renamed += 1
    print(f"Renamed {renamed} files.")

bulk_rename("/path/to/photos", "IMG_", "vacation_2025_")

Script 3: Automated File Backup

import shutil
import zipfile
from pathlib import Path
from datetime import datetime

def backup_folder(source: str, backup_dir: str):
    source_path = Path(source)
    backup_path = Path(backup_dir)
    backup_path.mkdir(parents=True, exist_ok=True)
    
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    zip_name = f"{source_path.name}_backup_{timestamp}.zip"
    zip_path = backup_path / zip_name
    
    with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
        for file in source_path.rglob("*"):
            if file.is_file():
                zf.write(file, file.relative_to(source_path))
    
    print(f"Backup created: {zip_path}")

backup_folder("/path/to/projects", "/path/to/backups")

Category 2: Email Automation

Script 4: Send Automated HTML Email

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

def send_email(to: str, subject: str, body_html: str):
    sender = "your@gmail.com"
    password = "your_app_password"  # Use Gmail App Password
    
    msg = MIMEMultipart("alternative")
    msg["Subject"] = subject
    msg["From"] = sender
    msg["To"] = to
    msg.attach(MIMEText(body_html, "html"))
    
    with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
        server.login(sender, password)
        server.sendmail(sender, to, msg.as_string())
    
    print(f"Email sent to {to}")

send_email(
    "recipient@example.com",
    "Weekly Report",
    "<h1>Report</h1><p>Your weekly summary...</p>"
)

Setup note: For Gmail, create an App Password (Google Account → Security → App passwords). Never use your main password in scripts.

Script 5: Email with Attachment

from email.mime.base import MIMEBase
from email import encoders
import os

def send_email_with_attachment(to: str, subject: str, body: str, file_path: str):
    # ... (same setup as Script 4)
    
    with open(file_path, "rb") as f:
        attachment = MIMEBase("application", "octet-stream")
        attachment.set_payload(f.read())
    encoders.encode_base64(attachment)
    attachment.add_header(
        "Content-Disposition",
        f"attachment; filename={os.path.basename(file_path)}"
    )
    msg.attach(attachment)

Category 3: Web Scraping and Data Collection

For a complete guide on web scraping with Python, see our Python web scraping guide for beginners.

Script 6: Scrape and Monitor a Price

import requests
from bs4 import BeautifulSoup
import json
from pathlib import Path
from datetime import datetime

def check_price(url: str, css_selector: str) -> float:
    headers = {"User-Agent": "Mozilla/5.0 (compatible)"}
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, "html.parser")
    price_text = soup.select_one(css_selector).text
    price = float(price_text.replace("$", "").replace(",", "").strip())
    return price

def track_price(url: str, selector: str, target_price: float):
    current_price = check_price(url, selector)
    entry = {"date": datetime.now().isoformat(), "price": current_price}
    
    history_file = Path("price_history.json")
    history = json.loads(history_file.read_text()) if history_file.exists() else []
    history.append(entry)
    history_file.write_text(json.dumps(history, indent=2))
    
    if current_price <= target_price:
        print(f"PRICE ALERT: ${current_price} (target: ${target_price})")

Script 7: Download All Images from a Webpage

import requests
from bs4 import BeautifulSoup
from pathlib import Path
from urllib.parse import urljoin

def download_images(url: str, output_dir: str):
    output = Path(output_dir)
    output.mkdir(exist_ok=True)
    
    response = requests.get(url, headers={"User-Agent": "Mozilla/5.0"})
    soup = BeautifulSoup(response.text, "html.parser")
    
    downloaded = 0
    for img in soup.find_all("img"):
        src = img.get("src")
        if not src:
            continue
        full_url = urljoin(url, src)
        filename = full_url.split("/")[-1].split("?")[0]
        
        img_data = requests.get(full_url).content
        (output / filename).write_bytes(img_data)
        downloaded += 1
    
    print(f"Downloaded {downloaded} images to {output_dir}")

Category 4: Spreadsheet and Data Automation

Script 8: Process CSV and Generate Report

import pandas as pd
from datetime import datetime

def monthly_expense_report(csv_file: str):
    df = pd.read_csv(csv_file, parse_dates=["date"])
    df["month"] = df["date"].dt.to_period("M")
    
    monthly = df.groupby(["month", "category"])["amount"].sum().unstack(fill_value=0)
    
    report_name = f"expense_report_{datetime.now().strftime('%Y%m')}.xlsx"
    with pd.ExcelWriter(report_name, engine="openpyxl") as writer:
        monthly.to_excel(writer, sheet_name="Monthly Summary")
        df.to_excel(writer, sheet_name="Raw Data", index=False)
    
    print(f"Report saved: {report_name}")
    return monthly

monthly_expense_report("expenses.csv")

Script 9: Combine Multiple Excel Files

import pandas as pd
from pathlib import Path

def combine_excel_files(folder: str, output: str):
    all_data = []
    for file in Path(folder).glob("*.xlsx"):
        df = pd.read_excel(file)
        df["source_file"] = file.name
        all_data.append(df)
    
    combined = pd.concat(all_data, ignore_index=True)
    combined.to_excel(output, index=False)
    print(f"Combined {len(all_data)} files → {output}")

combine_excel_files("monthly_reports/", "combined_2025.xlsx")

Category 5: API Integration Automation

Script 10: Send Slack Notification

import requests

def send_slack_message(webhook_url: str, message: str, channel: str = "#general"):
    payload = {"text": message, "channel": channel}
    response = requests.post(webhook_url, json=payload)
    return response.status_code == 200

# Create a webhook URL in Slack: Workspace settings → Incoming Webhooks
WEBHOOK = "https://hooks.slack.com/services/YOUR/WEBHOOK/URL"
send_slack_message(WEBHOOK, "Daily report is ready! ✅")

Script 11: Automated GitHub Repository Stats

import requests

def get_repo_stats(owner: str, repo: str) -> dict:
    url = f"https://api.github.com/repos/{owner}/{repo}"
    response = requests.get(url)
    data = response.json()
    return {
        "stars": data["stargazers_count"],
        "forks": data["forks_count"],
        "open_issues": data["open_issues_count"],
        "last_push": data["pushed_at"],
    }

stats = get_repo_stats("python", "cpython")
print(f"Python CPython: {stats['stars']} stars, {stats['open_issues']} open issues")

Script 12: Scheduled Daily Summary Email

import schedule
import time
import requests
from datetime import date

def generate_and_send_daily_summary():
    # Get today's data (example: crypto prices)
    btc = requests.get("https://api.coinbase.com/v2/prices/BTC-USD/spot").json()
    price = btc["data"]["amount"]
    
    body = f"""
    <h2>Daily Summary — {date.today()}</h2>
    <p>BTC Price: ${price}</p>
    """
    send_email("you@example.com", f"Daily Summary {date.today()}", body)

schedule.every().day.at("08:00").do(generate_and_send_daily_summary)

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

Category 6: System Automation

Script 13: Monitor Disk Space and Alert

import shutil
import os

def check_disk_space(threshold_gb: float = 5.0):
    total, used, free = shutil.disk_usage("/")
    free_gb = free / (1024 ** 3)
    
    if free_gb < threshold_gb:
        print(f"WARNING: Only {free_gb:.1f} GB free on disk!")
        # Add send_slack_message() or send_email() here
    else:
        print(f"Disk OK: {free_gb:.1f} GB free")

check_disk_space(threshold_gb=10.0)

Script 14: Automated Screenshot Taker

import subprocess
import time
from pathlib import Path
from datetime import datetime

def take_screenshots(interval_minutes: int, output_dir: str, duration_hours: int):
    output = Path(output_dir)
    output.mkdir(exist_ok=True)
    
    end_time = time.time() + duration_hours * 3600
    while time.time() < end_time:
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = output / f"screenshot_{timestamp}.png"
        
        # Mac
        subprocess.run(["screencapture", "-x", str(filename)])
        # Windows: subprocess.run(["snippingtool", "/clip"])
        
        time.sleep(interval_minutes * 60)

Category 7: Text and PDF Processing

Script 15: Extract Text from PDFs

import pdfplumber
from pathlib import Path

def extract_pdf_text(pdf_path: str) -> str:
    with pdfplumber.open(pdf_path) as pdf:
        text = "\n".join(page.extract_text() or "" for page in pdf.pages)
    return text

def batch_extract_pdfs(folder: str):
    for pdf_file in Path(folder).glob("*.pdf"):
        text = extract_pdf_text(str(pdf_file))
        output_file = pdf_file.with_suffix(".txt")
        output_file.write_text(text, encoding="utf-8")
        print(f"Extracted: {pdf_file.name} → {output_file.name}")

Script 16: Find and Replace in Multiple Files

from pathlib import Path

def bulk_find_replace(folder: str, find: str, replace: str, file_ext: str = ".txt"):
    count = 0
    for file in Path(folder).rglob(f"*{file_ext}"):
        content = file.read_text(encoding="utf-8")
        if find in content:
            file.write_text(content.replace(find, replace), encoding="utf-8")
            count += 1
    print(f"Replaced '{find}' in {count} files")

Category 8: Notification and Monitoring Scripts

Script 17: Website Uptime Monitor

import requests
import time
from datetime import datetime

def monitor_website(url: str, interval_seconds: int = 60):
    print(f"Monitoring {url} every {interval_seconds}s...")
    while True:
        try:
            response = requests.get(url, timeout=10)
            status = "UP" if response.status_code == 200 else f"ERROR {response.status_code}"
        except requests.ConnectionError:
            status = "DOWN"
        
        timestamp = datetime.now().strftime("%H:%M:%S")
        print(f"[{timestamp}] {url}: {status}")
        
        if status != "UP":
            print("ALERT: Site is down!")
            # Add notification here
        
        time.sleep(interval_seconds)

Script 18: Python-Powered Clipboard Manager

import pyperclip
import time
import json
from pathlib import Path
from datetime import datetime

def clipboard_logger(max_entries: int = 100):
    history_file = Path("clipboard_history.json")
    history = []
    last_content = ""
    
    print("Logging clipboard... Ctrl+C to stop")
    try:
        while True:
            current = pyperclip.paste()
            if current != last_content and current.strip():
                entry = {"time": datetime.now().isoformat(), "content": current}
                history.append(entry)
                if len(history) > max_entries:
                    history.pop(0)
                history_file.write_text(json.dumps(history, indent=2))
                last_content = current
            time.sleep(0.5)
    except KeyboardInterrupt:
        print(f"\nLogged {len(history)} clipboard entries.")

Scripts 19–20: Combining Everything

Script 19: Automated Weekly Report Generator

This combines file reading, data processing, and email sending — a complete automation pipeline.

import pandas as pd
from pathlib import Path
from datetime import date, timedelta

def generate_weekly_report(data_dir: str, email_to: str):
    # Load all CSV files from the past week
    week_ago = date.today() - timedelta(days=7)
    all_data = []
    for csv_file in Path(data_dir).glob("*.csv"):
        df = pd.read_csv(csv_file, parse_dates=["date"])
        df = df[df["date"].dt.date >= week_ago]
        all_data.append(df)
    
    if not all_data:
        print("No data for this week")
        return
    
    combined = pd.concat(all_data)
    summary = combined.groupby("category")["amount"].sum()
    
    table_html = summary.to_frame().to_html()
    email_body = f"<h2>Weekly Report</h2>{table_html}"
    
    send_email(email_to, f"Weekly Report — {date.today()}", email_body)
    print("Weekly report sent!")

Script 20: AI-Powered File Categorizer

This script reads file contents and uses an AI API to suggest categories — combining automation with AI.

import anthropic
from pathlib import Path

def ai_categorize_file(file_path: str) -> str:
    content = Path(file_path).read_text(encoding="utf-8", errors="ignore")[:2000]
    
    client = anthropic.Anthropic()
    response = client.messages.create(
        model="claude-haiku-4-5-20251001",
        max_tokens=50,
        messages=[{
            "role": "user",
            "content": f"Categorize this document in 1-3 words: {content}"
        }]
    )
    return response.content[0].text.strip()

Frequently Asked Questions

What can Python automate?

Files, email, web scraping, API calls, spreadsheets, system tasks, browser actions, image processing, PDFs, and notifications. If it's repetitive on a computer, Python can likely automate it.

How do I run scripts on a schedule?

Windows Task Scheduler, Mac/Linux cron, or the schedule library for in-script scheduling. GitHub Actions for cloud-based scheduling.

What libraries are most useful for automation?

requests, pathlib/shutil, pandas, smtplib, BeautifulSoup, schedule, and pyautogui cover 90% of automation use cases.

Is Python good for automation?

Yes — arguably the best language for automation due to library breadth, readable syntax, and cross-platform compatibility.


Final Thoughts

Automation is where Python delivers immediate, practical value. Every script above solves a real problem that someone has. Start with whichever category matches your actual repetitive work.

The habit that makes the difference: whenever you do something on a computer for the second time and think "I'll have to do this again," open a Python file and start automating it. The up-front cost is small; the ongoing savings compound.

For the file handling fundamentals behind many of these scripts, see our Python file handling guide. And for learning how to build the REST APIs that these automation scripts often call, our FastAPI tutorial covers API development from scratch.

Share this article:

Frequently Asked Questions

Python can automate almost any repetitive computer task: file organization and renaming, sending emails and notifications, web scraping and data collection, interacting with APIs, spreadsheet processing, scheduled data backups, browser automation, desktop GUI automation, image processing, PDF manipulation, and system monitoring. The practical limit is whether there's a Python library for the interface you want to automate — and there almost always is.
A

AiTechWorlds Team

✓ Verified Writer

The AiTechWorlds team is passionate about AI, technology, and education. We create high-quality, research-backed content to help you learn, grow, and succeed in the modern digital world.

Related Articles

10K+ Members Growing Daily

Get Free AI Notes Daily

Join AiTechWorlds on Telegram and get daily AI tips, prompt engineering templates, coding resources, and exclusive content — 100% free!

📚 Free Study Notes🤖 AI Tips Daily⚡ Prompt Templates💻 Coding Resources
Join Free Channel

No spam. Leave anytime.

!