10 Python Automation Scripts That Still Work (Tested, With Failure Modes)

Most Python automation tutorials were written for a Python that no longer exists. Gmail stopped accepting plain passwords over SMTP. imghdr left the standard library. PyPDF2 was folded into pypdf. The most-copied YouTube-downloader library hasn’t shipped a release in about three and a half years.

This guide gives you ten scripts that run on current Python, each with the way it will eventually break, plus a break-even formula so you only automate what pays for itself.

Last updated: 16 November 2026 · Reading time: ~15 minutes · Recommended Python: 3.11 or newer


Before you copy any code: what changed

ChangeWhat it means for you
Python 3.9 reached end of life in October 2025No more security fixes. Selenium dropped it from version 4.37.
Python 3.10 reached end of life in October 2026Still runs, but gets no patches. Use 3.11, 3.12, 3.13 or 3.14. Python 3.15 shipped in October 2026; give your libraries a few months before moving production scripts to it.
imghdr and cgi were removed in Python 3.13 (PEP 594)Tutorials that import them fail on 3.13+. Pillow identifies image formats itself.
Gmail no longer accepts your normal password over SMTPGoogle switched off “less secure apps” in stages (personal accounts in 2022, Workspace by 2025). You need an app password (2-Step Verification on) or OAuth.
PyPDF2 is deprecatedIts development continues as pypdf. This guide uses pypdf.
pytube is effectively abandonedIts last PyPI release, 15.0.0, is roughly 1,288 days old as of today. See Script 9.

How these scripts were checked

Every script below was run on Python 3.12.3 on Linux on 16 November 2026. Here is exactly what that covers, so you can judge how far to trust each one:

#ScriptWhat was verified
1File sorterRan end-to-end on a test folder: dry run, real move, name collisions, partial downloads skipped
2Email senderDry run and the safety cap only. No real email was sent.
3ScraperRan against a local test server, including the “selector matched nothing” alert
4BackupRan 7 times with rotation; verified archive integrity check
5Report generatorRan on a sample CSV; output re-read with openpyxl
6Image processorRan on PNG with transparency and WebP; a non-image file was skipped cleanly
7PDF extractorDigital PDF and a scanned (image-only) PDF with Tesseract OCR
8SeleniumImport and syntax only. No browser was launched.
9Dependency checkerRan against the live PyPI API
10SchedulingNot run (needs hours of runtime). Commands use standard cron and Task Scheduler syntax.

Not tested: Windows, macOS, Python 3.14 and 3.15. Treat those as “probably fine, verify first.”


The cost of manual work, honestly

Productivity statistics on automation are usually vague, so this guide doesn’t lean on any. You can compute your own number in 30 seconds:

annual hours saved = runs per week × minutes per run × 52 ÷ 60
break-even (weeks) = build hours ÷ (runs per week × minutes per run ÷ 60)

Worked example: a 15-minute task you do 5 times a week.

  • Time saved: 5 × 15 × 52 ÷ 60 = 65 hours a year
  • At $36/hour, that’s about $2,340 a year
  • If the script takes 2 hours to build and test, you break even in 1.6 weeks

Then subtract upkeep. As a rough rule of thumb (our estimate, not a studied figure), budget 2 to 4 hours per script per year for library updates and the occasional breakage. A script that saves 10 hours a year and costs 4 to maintain is a weak trade.

Rule of thumb: automate when break-even is under three months. Past six months, skip it unless the task will repeat for years.


The 10 scripts

Ordered from simplest to most involved. Start with Script 1 if you’ve never automated anything.

Install once

bash

python3 -m venv automation_env
source automation_env/bin/activate        # macOS / Linux
# automation_env\Scripts\activate         # Windows

pip install --upgrade pip
pip install requests beautifulsoup4 pandas openpyxl Pillow pypdf pytesseract pdf2image selenium schedule

OCR (Script 7) also needs two system programs: Tesseract and Poppler. macOS: brew install tesseract poppler · Ubuntu: sudo apt install tesseract-ocr poppler-utils · Windows: install Tesseract from the UB-Mannheim builds and Poppler separately.


1. File organizer

Fixes: a Downloads folder with thousands of unsorted files.
Needs: nothing beyond the standard library.

The version below is safer than the usual tutorial script: it runs in dry-run mode by default, sorts by each file’s modified date (not today’s date), never overwrites, and ignores unfinished downloads.

python

"""Sort Downloads into Organized/<Category>/<YYYY-MM> using each file's modified date."""
import shutil
import sys
from datetime import datetime
from pathlib import Path

WATCH = Path.home() / "Downloads"
DEST = Path.home() / "Organized"
SKIP_SUFFIXES = {".crdownload", ".part", ".tmp", ".download"}  # unfinished downloads
CATEGORIES = {
    "Images": {".jpg", ".jpeg", ".png", ".gif", ".webp", ".heic"},
    "Documents": {".pdf", ".docx", ".xlsx", ".pptx", ".txt", ".csv"},
    "Code": {".py", ".js", ".html", ".json", ".sh"},
    "Archives": {".zip", ".tar", ".gz", ".7z"},
    "Media": {".mp4", ".mp3", ".mov", ".wav"},
}

def category_for(path: Path) -> str:
    ext = path.suffix.lower()
    return next((c for c, exts in CATEGORIES.items() if ext in exts), "Other")

def organize(watch: Path = WATCH, dest: Path = DEST, dry_run: bool = True) -> int:
    moved = 0
    for f in watch.iterdir():
        if not f.is_file() or f.name.startswith(".") or f.suffix.lower() in SKIP_SUFFIXES:
            continue
        month = datetime.fromtimestamp(f.stat().st_mtime).strftime("%Y-%m")
        target_dir = dest / category_for(f) / month
        target = target_dir / f.name
        n = 1
        while target.exists():  # never overwrite
            target = target_dir / f"{f.stem}_{n}{f.suffix}"
            n += 1
        print(f"{'WOULD MOVE' if dry_run else 'MOVED'}: {f.name} -> {target.relative_to(dest)}")
        if not dry_run:
            target_dir.mkdir(parents=True, exist_ok=True)
            try:
                shutil.move(str(f), str(target))
            except PermissionError:
                print(f"SKIPPED (in use): {f.name}")
                continue
        moved += 1
    return moved

if __name__ == "__main__":
    organize(dry_run="--run" not in sys.argv)

Run python file_sorter.py to preview, then python file_sorter.py --run to move files.

How it breaks: a full destination drive. The script doesn’t check free space, so add shutil.disk_usage(dest).free before moving large files to an external or network disk.


2. Email sender (Gmail)

Fixes: sending dozens of templated emails by hand.
Needs: the standard library, a Gmail app password.

  1. Turn on 2-Step Verification for the Google account.
  2. Create an app password at myaccount.google.com/apppasswords.
  3. Store it as an environment variable. Never paste it into the script.

python

import os
import smtplib
import ssl
import time
from email.message import EmailMessage

DAILY_CAP = 400  # stay under Gmail's 500/day personal limit

def send_batch(recipients, subject, body, dry_run=True):
    user = os.environ["EMAIL_USER"]
    password = os.environ["EMAIL_APP_PASSWORD"]  # 16-character app password
    if len(recipients) > DAILY_CAP:
        raise SystemExit(f"{len(recipients)} recipients exceeds the safety cap of {DAILY_CAP}")
    if dry_run:
        print(f"DRY RUN: would send {len(recipients)} emails")
        return
    context = ssl.create_default_context()
    with smtplib.SMTP("smtp.gmail.com", 587, timeout=30) as server:
        server.starttls(context=context)
        server.login(user, password)
        for to in recipients:
            msg = EmailMessage()
            msg["From"], msg["To"], msg["Subject"] = user, to, subject
            msg.set_content(body)
            server.send_message(msg)
            print(f"sent: {to}")
            time.sleep(1)  # avoid burst throttling

How it breaks:

  • Daily limits. Personal Gmail is capped at roughly 500 recipients per day (about 2,000 on Google Workspace). Hit the cap and sending stops until the window resets. Check Google’s current limits before a big send.
  • Password changes. Changing your Google password revokes every app password, and the script starts failing with a 535 error.
  • Deliverability. Bulk mail from a personal address without SPF, DKIM and DMARC lands in spam. Gmail and Yahoo enforce stricter rules on senders above 5,000 messages a day. For cold outreach or newsletters, use a dedicated sending service (SendGrid, Amazon SES, Postmark).

3. Polite web scraper

Fixes: copying prices, listings, or headlines into a spreadsheet by hand.
Needs: requests, beautifulsoup4.

This version checks robots.txt first and raises an error when a selector matches nothing, because a scraper that silently returns an empty list is how bad data reaches reports.

python

import time
from urllib import robotparser
from urllib.parse import urlparse

import requests
from bs4 import BeautifulSoup

UA = "MyResearchBot/1.0 (contact: you@example.com)"

def allowed(url: str) -> bool:
    root = f"{urlparse(url).scheme}://{urlparse(url).netloc}"
    rp = robotparser.RobotFileParser(root + "/robots.txt")
    rp.read()
    return rp.can_fetch(UA, url)

def titles(url: str, selector: str = "h2") -> list[str]:
    if not allowed(url):
        raise PermissionError(f"robots.txt disallows {url}")
    r = requests.get(url, headers={"User-Agent": UA}, timeout=10)
    r.raise_for_status()
    found = [el.get_text(strip=True) for el in BeautifulSoup(r.text, "html.parser").select(selector)]
    if not found:  # a silent zero is how scrapers rot
        raise ValueError(f"selector {selector!r} matched nothing on {url} - page layout changed?")
    return found

if __name__ == "__main__":
    for u in ["https://example.com/"]:
        print(titles(u, "h1"))
        time.sleep(2)  # be gentle between requests

How it breaks:

  • Redesigns change the HTML, and your selector stops matching (the script above will tell you).
  • JavaScript-rendered pages return an empty shell to requests. Look for the site’s JSON endpoint or an official API before reaching for a browser.
  • Blocking (HTTP 429/403, CAPTCHAs). Slow down, or use the official API.
  • Legal and contractual limits. Courts have treated scraping publicly available data differently from breaching a site’s terms, and the hiQ v. LinkedIn litigation ended with a finding against the scraper on contract grounds. Read the site’s terms, and get legal advice for commercial use. This is general information, not legal advice.

4. Verified backups with rotation

Fixes: the afternoon you discover a folder is gone.
Needs: the standard library.

The classic backup script prints “✓ Backup complete” even when the archive is corrupt. This one writes to a temporary name, verifies the archive, and only then keeps it.

python

import zipfile
from datetime import datetime
from pathlib import Path

SOURCE = Path("/path/to/important/files")
BACKUPS = Path("/path/to/backups")
KEEP = 5

def create_backup(source: Path = SOURCE, backups: Path = BACKUPS, keep: int = KEEP) -> Path:
    backups.mkdir(parents=True, exist_ok=True)
    files = [p for p in source.rglob("*") if p.is_file()]
    final = backups / f"backup_{datetime.now():%Y%m%d_%H%M%S}.zip"
    tmp = final.with_suffix(".zip.partial")
    with zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED) as z:
        for p in files:
            z.write(p, p.relative_to(source))
    with zipfile.ZipFile(tmp) as z:  # verify before trusting it
        if z.testzip() is not None or len(z.namelist()) != len(files):
            tmp.unlink()
            raise RuntimeError("Backup verification failed - archive deleted")
    tmp.rename(final)
    for old in sorted(backups.glob("backup_*.zip"), key=lambda p: p.stat().st_mtime)[:-keep]:
        old.unlink()
    return final

How it breaks: a backup that lives on the same disk as the original protects you from deleted files, not from a dead drive. Follow the 3-2-1 rule: three copies, two kinds of storage, one off-site. And test a restore at least once, because an untested backup is a hope, not a backup.


5. Spreadsheet report generator

Fixes: monthly reports rebuilt by hand from the same CSV exports.
Needs: pandas, openpyxl.

python

import pandas as pd
from openpyxl.styles import Font, PatternFill

def build_report(csv_path="sales_data.csv", out="Q2_Report.xlsx"):
    df = pd.read_csv(csv_path)
    df["total"] = df["q1_sales"] + df["q2_sales"]  # real values, not formulas
    with pd.ExcelWriter(out, engine="openpyxl") as xl:
        df.to_excel(xl, index=False, sheet_name="Sales")
        ws = xl.sheets["Sales"]
        for cell in ws[1]:
            cell.font = Font(bold=True, color="FFFFFF")
            cell.fill = PatternFill("solid", start_color="4472C4")
        for col in ws.columns:
            ws.column_dimensions[col[0].column_letter].width = max(len(str(c.value or "")) for c in col) + 3
    return out

Expected CSV columns: product, q1_sales, q2_sales.

How it breaks: formulas written by openpyxl (like =B2+C2) have no cached value until the file is opened in Excel, so anything that reads the file programmatically sees empty cells. That’s why this script computes totals in pandas and writes plain numbers. If you need live formulas for humans, add them in a second pass.


6. Image batch processor

Fixes: resizing and compressing hundreds of photos.
Needs: Pillow.

python

from pathlib import Path
from PIL import Image, ImageOps

def batch_process(src="originals", dst="processed", max_width=1920, quality=85):
    src, dst = Path(src), Path(dst)
    dst.mkdir(exist_ok=True)
    for p in src.iterdir():
        try:
            with Image.open(p) as img:
                if img.format not in {"JPEG", "PNG", "WEBP"}:
                    continue
                img = ImageOps.exif_transpose(img)  # respect phone-camera rotation
                if img.width > max_width:
                    img = img.resize((max_width, round(img.height * max_width / img.width)), Image.Resampling.LANCZOS)
                out = dst / f"{p.stem}.jpg"
                img.convert("RGB").save(out, "JPEG", quality=quality, optimize=True)
                print(f"{p.name}: {p.stat().st_size // 1024} KB -> {out.stat().st_size // 1024} KB")
        except Exception as e:  # one bad file must not stop the batch
            print(f"FAILED {p.name}: {e}")

Pillow reads the real format from the file contents (img.format), which is the modern replacement for the removed imghdr module.

How it breaks:

  • Converting PNGs with transparency to JPEG fills transparent areas with black. Paste onto a white background first if that matters.
  • Two files with the same name but different extensions (logo.png, logo.webp) collide on output. Add the extension to the output name if your folder has both.
  • For a handful of photos, a manual edit is faster than writing this.

7. PDF text extractor with OCR fallback

Fixes: copy-pasting text out of PDFs.
Needs: pypdf, pytesseract, pdf2image, plus Tesseract and Poppler installed.

Digital PDFs already contain a text layer, so extraction is instant and exact. Only scanned pages need OCR. This version decides page by page, which handles mixed documents.

python

import pytesseract
from pdf2image import convert_from_path
from pypdf import PdfReader

def extract_text(path: str, min_chars: int = 25) -> str:
    """Use the embedded text layer per page; OCR only the pages that have none."""
    reader = PdfReader(path)
    out = []
    for i, page in enumerate(reader.pages):
        text = (page.extract_text() or "").strip()
        if len(text) < min_chars:  # likely a scanned page
            img = convert_from_path(path, first_page=i + 1, last_page=i + 1, dpi=300)[0]
            text = pytesseract.image_to_string(img).strip()
        out.append(text)
    return "\n\n".join(out)

How it breaks: OCR quality depends on the scan. Clean 300 dpi pages come out well; faded, skewed or handwritten pages do not. Never pipe OCR output straight into financial or legal workflows without a human check on the numbers.


8. Browser automation with Selenium

Fixes: repetitive form-filling and clicking in a real browser.
Needs: selenium (Python 3.10 or newer; use 3.11+).

Selenium includes Selenium Manager, which downloads the matching browser driver for you. The old ChromeDriver version-mismatch dance is gone.

python

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

options = webdriver.ChromeOptions()
options.add_argument("--headless=new")
driver = webdriver.Chrome(options=options)  # Selenium Manager fetches the driver

try:
    driver.get("https://example.com/form")
    wait = WebDriverWait(driver, 10)

    wait.until(EC.visibility_of_element_located((By.ID, "name"))).send_keys("Jane Smith")
    driver.find_element(By.ID, "email").send_keys("jane@example.com")
    wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[type='submit']"))).click()

    wait.until(EC.url_contains("thank-you"))  # confirm it worked, don't assume
    print("Form submitted")
finally:
    driver.quit()

Not run in testing. This script was syntax-checked and imported, but no browser was launched. Test it against your own form.

How it breaks: use explicit waits instead of time.sleep(), because fixed sleeps are both slower and flakier. And always verify the result (a confirmation URL or message), since a click that “worked” may not have submitted anything. Sites protected by bot detection will block default Selenium; respect their rules rather than trying to evade them.


9. Dependency health checker

Fixes: discovering that a library you depend on died.

This slot used to belong to a pytube walkthrough. Here’s why it was replaced. As of 16 November 2026, PyPI shows:

PackageLatest versionLast releaseVerdict
pytube15.0.0~1,288 days agoUnmaintained; reports of HTTP 400/410 errors are common
pytubefix (fork)11.2.131 days agoMaintained, yet its issue tracker still shows 403 errors and stream-protection failures

Two lessons. First, “there’s an active fork” doesn’t mean “it works”: scrapers of third-party platforms break whenever the platform changes. Second, downloading from platforms like YouTube may violate their terms of service, so this guide doesn’t provide downloader code.

What you can automate is checking the health of your own dependencies before you build on them:

python

import sys
from datetime import datetime, timezone
import requests

def check(package: str) -> None:
    data = requests.get(f"https://pypi.org/pypi/{package}/json", timeout=10).json()
    version = data["info"]["version"]
    files = data["releases"].get(version, [])
    uploaded = max(datetime.fromisoformat(f["upload_time_iso_8601"].replace("Z", "+00:00")) for f in files)
    age = (datetime.now(timezone.utc) - uploaded).days
    flag = "OK" if age < 365 else "CHECK - no release in over a year"
    print(f"{package} {version}: last release {age} days ago | requires {data['info']['requires_python']} | {flag}")

if __name__ == "__main__":
    for name in sys.argv[1:] or ["requests"]:
        check(name)

Run python dep_check.py requests pypdf pillow. Sample output from the test run:

requests 2.34.2: last release 185 days ago | requires >=3.10 | OK
pytube 15.0.0: last release 1288 days ago | requires >=3.7 | CHECK - no release in over a year

Interpret with care. An old release date isn’t automatically bad: small, finished libraries can be stable for years. Combine it with the library’s issue tracker: many recent unanswered bug reports plus no releases is the real warning sign.


10. Scheduling: cron first, schedule second

Fixes: scripts you have to remember to run.

The schedule library is fine for learning and for scripts on an always-on machine, but it only works while its Python process is running. Reboot, and it’s gone. For anything you rely on, use the operating system’s scheduler:

bash

# Linux / macOS: crontab -e   (runs the backup daily at 02:00 and logs output)
0 2 * * * /home/you/automation_env/bin/python /home/you/backup_job.py >> /home/you/automation.log 2>&1

bat

:: Windows (Command Prompt)
schtasks /Create /SC DAILY /ST 02:00 /TN "DailyBackup" /TR "C:\automation_env\Scripts\python.exe C:\scripts\backup_job.py"

Use the full path to the virtual environment’s Python, not just, or the job will run without your installed packages. In the cloud, a scheduled function (AWS Lambda with EventBridge, or Google Cloud Scheduler) removes the always-on machine entirely.


Don’t let scripts fail silently

Add a log to every script that runs unattended. It takes ten lines and is the cheapest reliability upgrade available:

python

import logging

logging.basicConfig(
    filename="automation.log",
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s",
)

try:
    result = main()
    logging.info("Success: %s", result)
except Exception:
    logging.exception("Run failed")  # logs the full traceback
    raise

Then look at the log. A script that fails every night for six months while you assume it works is worse than no script.

Quick health check before you trust any script

CheckHowWarning sign
Python versionpython --versionBelow 3.11, or end of life
Removed modulesSearch for imghdr, cgi, distutilsImport errors on Python 3.12+
Library activityScript 9, then the issue trackerA year without a release plus unanswered bugs
Error handlingLook for try/except and loggingFailures that print nothing
Backups before bulk editsDoes the script touch originals?Any script that renames or deletes

What not to automate

TaskVerdictWhy
Daily file cleanupAutomateFrequent, predictable, low risk
BackupsAutomateCheap to build, painful to lack
Templated emailsAutomateRepetitive and easy to verify
Monthly reportsMaybeRare enough that upkeep can outweigh savings
One-time migrationsSkipFaster by hand than building and testing a script
Judgment calls (hiring, pricing, creative work)SkipThe hard part isn’t the typing
Processes that change every monthSkipYou’ll spend more time fixing the script than doing the task

Frequently asked questions

Which Python version should I use for automation in 2026? Python 3.11, 3.12, 3.13, or 3.14. Python 3.9 and 3.10 are both end-of-life. Python 3.15 was released in October 2026; wait for your key libraries to confirm support before moving production jobs.

Why does my Gmail script fail with a 535 authentication error? Almost always because it uses your normal account password. Gmail needs an app password (with 2-Step Verification enabled) or OAuth. The error also appears after you change your Google password, because that revokes existing app passwords.

Is PyPDF2 still safe to use? It still installs, but active development moved to pypdf. New projects should use; the extraction code in Script 7 works with it.

What replaced imghdr? Nothing in the standard library. Use Pillow (Image.open(path).format) or the filetype package. Both read the real file signature.

Is web scraping legal? It depends on the data, the site’s terms, your jurisdiction, and what you do with the results. Public data isn’t automatically free to collect at scale. Check the terms and robots.txtask a lawyer if the use is commercial.

How long does a script stay working? No fixed answer. Scripts that use only the standard library last the longest. Anything touching a third-party website or API is the most likely to break.


The takeaway

Start with Script 1 this week and run it in dry-run mode for a few days before letting it move anything. Add logging, measure the time you actually save, and only then automate the next task. The lasting skill here isn’t any one script. It’s knowing which tasks are worth automating, and noticing quickly when an automation stops working.

More Python and productivity guides at CodeTalentHub.


Sources

  1. Python Developer’s Guide: status of Python versions
  2. PEP 594: removing “dead batteries” from the standard library
  3. Selenium blog: ending support for Python 3.9
  4. Selenium on PyPI
  5. Google Workspace Updates: winding down less secure apps support
  6. pypdf documentation and PyPI page
  7. pytube on PyPI and pytubefix issue tracker
  8. Real Python: Python 3.14 release and Python 3.9 retirement
  9. PyPI JSON API (https://pypi.org/pypi/<package>/json), queried 16 November 2026 for the release dates in Script 9

Gmail sending limits and the Python 3.15 release date were checked against secondary sources; confirm against Google’s and python.org’s current pages before quoting them exactly.

1 thought on “10 Python Automation Scripts That Still Work (Tested, With Failure Modes)”

Leave a Comment