Skip to main content

10 Examples of Python Automation Scripts for Critical Tasks

These 10 Python automation scripts handle repetitive tasks like file management, data cleaning, web scraping, and reporting. Tested code, real results, beginner-friendly.

Posted July 14, 2026

Python automation scripts are short programs that perform repetitive tasks for you, such as sorting files, cleaning data, sending emails, and pulling information from websites. You write the Python code once, and the script runs the task the same way every time. That consistency is the point. It saves time and removes the human errors that creep into manual data entry.

This guide walks through 10 automation scripts you can run today. Every example was tested on Python 3.14, the current stable release of the Python programming language, and uses libraries that are actively maintained in 2026. That matters more than it sounds. Several top-ranking guides on this topic still teach deprecated tools like PyPDF2 and PyDrive, which now fail on modern installs.

Read: The 5 Best AI Coding Agents: Pros & Cons, Reviews, & Which is Best for You

What Are Python Automation Scripts?

A Python automation script is a file of Python code, saved with a .py extension, that completes a task without you doing the steps manually. Common automation tasks include file handling, renaming and moving multiple files, converting CSV files, scraping web pages, and sending scheduled emails.

Python became the default choice for automation for a simple reason. Its Python syntax reads close to plain English, so the language is beginner-friendly even if you have never programmed before. It also ships with useful built-in modules for file management and data structures like lists and dictionaries, and it has a massive ecosystem of external libraries for everything else, from web scraping to machine learning.

When you automate tasks using Python, you save time in two ways. The task itself runs faster, and you stop paying the mental cost of remembering to do it. You do not need to master Python basics before you automate your first task. Most of the scripts below are under 30 lines. Copy one, change the file path to match your machine, and run it.

Read: How to Become an AI Specialist

How to Run a Python Script in 2026

To run a Python script, install Python from Python.org, save your code in a file ending in .py, then open your terminal, type Python3 followed by the file name, and press Enter.

A few version notes worth knowing this year. Python 3.14 is the current stable release and the recommended version for new automation projects. Python 3.9 reached end of life in October 2025 and no longer receives security patches, so upgrade if you are still on it. If a script needs an external library, install it first with pip. For example, pip install requests adds the requests library used in several examples below.

One habit will save you hours of debugging later. Create a separate virtual environment for your automation projects with Python3 -m venv automation. This keeps each project's Python libraries isolated so upgrades in one script never break another.

1. Sort Files Into Folders Based on File Type

This script cleans a messy folder by moving every file into different folders based on its file type. Images go to an Images folder, PDFs to Documents, spreadsheets to Data, and so on.

File management is the most common first automation project for a reason. It touches a pain everyone has, and it teaches two workhorse modules at once. The pathlib module handles every file path, and import shutil gives you the move command.

import shutil from pathlib import Path folder = Path.home() / "Downloads" destinations = { ".jpg": "Images", ".png": "Images", ".webp": "Images", ".pdf": "Documents", ".docx": "Documents", ".csv": "Data", ".xlsx": "Data", ".json": "Data", } for item in folder.iterdir(): if item.is_file(): target_name = destinations.get(item.suffix.lower()) if target_name: target = folder / target_name target.mkdir(exist_ok=True) shutil.move(item, target / item.name) print(f"Moved {item.name} to {target_name}")

Point the script at any specified folder by changing the first line. Run it weekly, and your downloads folder stays organized without you thinking about it.

Tip from real users: Add a dry-run mode that prints what would move before anything actually moves. Several developers in the r/learnPython thread learned this the hard way after a script relocated files they needed.

2. Split a Massive PDF File and Extract Text

This script splits one giant PDF into separate documents by detecting where each new section starts, then names each output file automatically.

The idea comes straight from one of the best stories in the Reddit thread. A developer received a single 9,000-page PDF containing every client statement from a legacy vendor. Finding and printing each statement by hand would have taken days. His script searched each page for the phrase "Page 1 of", treated that as the start of a new statement, and split the whole archive in about 30 seconds.

The 2026 way to do this uses pypdf. The older PyPDF2 library that many tutorials still teach was deprecated and folded back into pypdf, so its old class names now throw errors.

from pypdf import PdfReader, PdfWriter reader = PdfReader("statements.pdf") writer = PdfWriter() part = 1 for page in reader.pages: text = page.extract_text() or "" if "Page 1 of" in text and len(writer.pages) > 0: with open(f"statement_{part}.pdf", "wb") as output: writer.write(output) writer = PdfWriter() part += 1 writer.add_page(page) with open(f"statement_{part}.pdf", "wb") as output: writer.write(output) print(f"Split complete. Created {part} files.")

The same extract_text() method also lets you pull the contents of any PDF into a plain text file for search, analysis, or the AI summary script in example seven.

3. Clean Messy Data in CSV Files

This script takes a raw CSV export and removes duplicate rows, drops empty rows, fills missing values, and standardizes column names in one pass.

Data cleaning is where automation pays off fastest for anyone who works with spreadsheets. Analysts widely report that preparing messy data consumes more of their week than the actual data analysis does, and every manual cleanup pass risks new mistakes. A pandas script applies the exact same rules to every export, which is also why clean pipelines matter so much in machine learning work. The model is only as good as the data you feed it.

The example below uses import pandas, the standard data library. Pandas 3.0 shipped in January 2026 and requires Python 3.11 or newer, so update both together.

import pandas as pd df = pd.read_csv("raw_sales.csv") df = df.drop_duplicates() df = df.dropna(how="all") # remove empty rows df["region"] = df["region"].fillna("Unknown") df.columns = df.columns.str.lower().str.replace(" ", "_") df.to_csv("clean_sales.csv", index=False) print(f"Cleaned file saved with {len(df)} rows.")

Run this on every export before it reaches a report or dashboard. The people reading your numbers will never know the script exists, and that is exactly the goal.

4. Build a JSON to CSV Converter

This CSV converter reads a JSON file and rewrites it as a spreadsheet-ready CSV in about ten lines of code.

APIs and modern apps usually hand you data in JSON format, while managers and finance teams live in spreadsheets. Translating between the two by hand is pure manual data entry, and it is precisely the kind of repetitive task Python removes. Both formats have built-in support, so no external libraries are needed. You use import json to read and import csv to write.

import csv import json with open("orders.json") as source: records = json.load(source) with open("orders.csv", "w", newline="") as output: writer = csv.DictWriter(output, fieldnames=records[0].keys()) writer.writeheader() writer.writerows(records) print(f"Converted {len(records)} records to CSV.")

The following example works for a flat list of records. If your JSON is nested, swap in pd.json_normalize() from pandas, which flattens nested fields into columns automatically.

5. Monitor a Website With Web Scraping

This script checks a web page on a schedule, pulls out the data you care about, and alerts you when something changes.

Web scraping is the most popular category of Python automation in the r/learnPython thread, and the use cases are wonderfully practical. One user scrapes a local venue's calendar and ranks upcoming bands by their streaming numbers. Another compares grocery prices across stores before shopping. A third watches a sold-out convention's ticket page every ten seconds and gets a phone alert the moment availability changes.

The standard toolkit is import requests to fetch the page, plus BeautifulSoup to parse it.

import requests from bs4 import BeautifulSoup url = "https://example.com/tickets" headers = {"User-Agent": "Mozilla/5.0"} response = requests.get(url, headers=headers, timeout=10) soup = BeautifulSoup(response.text, "html.parser") status = soup.find("span", class_="availability") if status and "sold out" not in status.text.lower(): print(f"Tickets available. Check {url} now.")

Two rules keep your scraping polite and reliable. Add a delay of a few seconds between requests so you never hammer someone's server, and check the site's robots.txt and terms before you scrape. For pages that load content with JavaScript, step up to Playwright, which has largely replaced Selenium as the browser automation tool of choice.

6. Send Personalized Emails From a CSV

This script sends personalized emails to a whole list of recipients, filling in each person's name and details from a CSV file.

Sending thirty nearly identical messages by hand is tedious, and it invites the classic mistake of pasting the wrong name above the wrong numbers. Automating the send removes that risk and produces faster sign-off from whoever is waiting on the information, because it arrives on time every time.

Python handles this with import smtplib from the standard library, which talks to your email provider's SMTP server. For Gmail, generate an app password in your Google account settings rather than using your real password, and store it in an environment variable instead of the script itself.

import csv import os import smtplib import ssl from email.message import EmailMessage sender = "[email protected]" app_password = os.environ["EMAIL_APP_PASSWORD"] context = ssl.create_default_context() with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server: server.login(sender, app_password) with open("recipients.csv") as source: for name, email, score in csv.reader(source): msg = EmailMessage() msg["Subject"] = "Your Q3 evaluation" msg["From"] = sender msg["To"] = email msg.set_content(f"Hi {name},\n\nYour Q3 score is {score}.") server.send_message(msg) print(f"Sent to {name}")

The script sends one message per row, so a 200-person list takes seconds. Pair it with the CSV cleaning script above, and your recipient data stays accurate too.

7. Summarize Reports Automatically With an AI API

This script downloads a document, extracts the text, and sends it to an AI model through api requests, returning a structured summary you can drop into a dashboard or email.

This is the automation that separates a 2026 workflow from a 2020 one, and it comes directly from the standout story in the Reddit thread. A financial analyst had a Monday ritual of downloading two market reports, reading them, and summarizing them for management. His script now runs at 6 a.m., pulls the PDFs, extracts the text, and asks an AI model for a summary in JSON format broken into fixed sections for performance, risks, and rates. A dashboard reads that json file, and leadership reviews everything on their iPads by 8 a.m. He does nothing.

The pattern below works with any major AI provider's API. Two settings make the output reliable enough to feed into other code. Set the temperature to 0 so the same input always produces the same output, and tell the model to respond only with JSON.

import json import os import requests report_text = open("weekly_report.txt").read() response = requests.post( "https://api.openai.com/v1/chat/completions", headers={"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}"}, json={ "model": "gpt-5-mini", "temperature": 0, "messages": [{ "role": "user", "content": "Summarize this report as JSON with keys " f"'performance', 'risks', 'rates':\n\n{report_text}" }], }, timeout=60, ) summary = json.loads(response.json()["choices"][0]["message"]["content"]) print(summary["risks"])

One caution from developers who run these pipelines daily. Always wrap the JSON parsing in error handling because models occasionally return malformed output, and check your provider's current model names since they change frequently.

8. Back Up Files to Google Drive

This script uploads a folder of files to Google Drive automatically, giving you an off-machine backup without dragging files into a browser.

A word of warning before the code. The PyDrive library that older tutorials recommend has been abandoned for years. The maintained path in 2026 is Google's official client, installed with pip install google-api-Python-client google-auth. You create a service account in Google Cloud Console, download its credentials JSON, and share your target Drive folder with the service account's email address.

import os from google.oauth2 import service_account from googleapiclient.discovery import build from googleapiclient.http import MediaFileUpload creds = service_account.Credentials.from_service_account_file( "credentials.json", scopes=["https://www.googleapis.com/auth/drive.file"], ) drive = build("drive", "v3", credentials=creds) folder_id = "YOUR_DRIVE_FOLDER_ID" for filename in os.listdir("backups"): media = MediaFileUpload(os.path.join("backups", filename)) drive.files().create( body={"name": filename, "parents": [folder_id]}, media_body=media, ).execute() print(f"Uploaded {filename}")

One developer in the thread runs a nightly version of this against his database exports. The process takes zero attention once scheduled, and on the day something goes wrong locally, the backup is already sitting in the cloud.

9. Batch Process Multiple Images

This script converts and resizes multiple images in one run, turning a folder of heavy JPGs into web-ready WebP files at a fraction of the size.

Anyone who publishes online knows this chore. You have forty photos; each needs to be a consistent width, and each needs to be converted to a lighter format before upload. Doing that one image at a time in an editor is exactly the kind of work Python should own. The Pillow library handles it, installed with pip install Pillow.

from pathlib import Path from PIL import Image source = Path("photos") output = Path("photos/web") output.mkdir(exist_ok=True) for file in source.glob("*.jpg"): with Image.open(file) as img: img.thumbnail((1600, 1600)) # resize photos, keep aspect ratio img.save(output / f"{file.stem}.webp", "WEBP", quality=80) print(f"Converted {file.name}") print("Done. Open the output folder to view image results.")

The thumbnail() method shrinks each image while keeping its proportions, so nothing gets stretched. Adjust the quality value to trade file size against sharpness. At 80, most photos drop dramatically in weight with no visible difference.

10. Monitor CPU Usage and Disk Space

This script watches your machine's CPU usage and disk space, then sends an alert when either crosses a threshold you set.

Monitoring rounds out any automation setup because scheduled scripts fail quietly when a disk fills up or a runaway process pins the CPU. Developers who run home servers, scraping jobs, or nightly backups all eventually add a watchdog like this. It uses psutil, installed with pip install psutil, and reuses the email pattern from script six.

import shutil import psutil cpu = psutil.cpu_percent(interval=1) disk = shutil.disk_usage("/") free_percent = disk.free / disk.total * 100 alerts = [] if cpu > 85: alerts.append(f"High CPU usage: {cpu}%") if free_percent < 10: alerts.append(f"Low disk space: {free_percent:.1f}% free") for alert in alerts: print(alert) # swap in the send_email() function from script 6

Schedule it to run every few minutes, and you will hear about problems before they take down the automations you depend on.

How to Schedule Python Automation Scripts

Task scheduling is what turns a script you run by hand into true automation that works while you sleep. You have three solid options in 2026, and the right one depends on your operating system and how the script needs to run.

  • Built-in OS schedulers are the most reliable choice - On Mac and Linux, cron runs any command on a timed schedule. The entry 0 6 * * 1 Python3 /path/to/report.py runs a script every Monday at 6 a.m., the exact setup behind the analyst's Monday report pipeline. On Windows, Task Scheduler does the same job through a visual interface, and the "run whether user is logged on or not" option keeps scripts working on a locked machine.
  • The schedule library keeps everything in Python - Install it with pip and write timing rules like schedule.every().day.at("06:00").do(job) in plain code. The tradeoff is that the script must stay running, so it suits always-on machines.
  • Cloud runners remove your computer from the equation - GitHub Actions can run a Python script on a cron schedule for free within generous limits, which is a popular choice for scrapers and monitors that need to run even when your laptop is closed.

Whichever you choose, add basic error handling first. Wrap risky steps in try and except blocks and log failures to a text file, so a bad network day does not silently kill a month of automated reports.

Read: AI Upskilling: Top Firms, Programs, & Tools for Training Your Workforce

Should You Tell Your Boss You Automated Your Job?

Yes, in most workplaces, disclosure protects you, though how you frame the conversation matters a great deal.

This question generated one of the liveliest debates in the r/learnPython thread. One commenter automated a daily task, told management, and was rewarded with more work at the same pay. Others quietly bank the saved hours. The honest middle ground most experienced developers land on looks like this. Company scripts running on company data are rarely something you can hide long term, and being the person who eliminated a tedious process is a genuinely strong career story. Frame the win in outcomes the business cares about. One thread member automated a 6-hour manual testing routine down to 15 minutes and made it part of the official build process, which became a resume line rather than a secret.

The exception is personal-productivity scripts that only touch your own workflow, like the file organizer in script one. Nobody needs a memo about your tidy downloads folder.

Start With One Script This Week

The fastest way to learn Python automation is to automate one real task this week. Pick the script closest to your most annoying repetitive task, change the file paths to match your machine, and run it.

You do not need a grand plan. The developers with the most impressive automation setups, the ones running scheduled report pipelines and self-monitoring backups, all started the same way. One script, one saved hour, and the confidence to automate the next thing. The financial analyst who reclaimed his Monday mornings began with a single download script. The developer who split 9,000 pages in 30 seconds was new to Python when he wrote it.

Every hour a script gives back is an hour you can spend on work that actually needs your judgment. That trade compounds fast.

Want to go further with AI and automation? If you are building these skills for your career, Leland's AI program offers structured training that takes you from scripts like these to full AI-powered workflows. You can also work one-on-one with an AI automation and agents coach or join a free upcoming AI automation event to learn from practitioners in real time.

See also: Top 10 AI Consultants and Experts

Read next:


FAQs

What is the best Python library for automation?

  • There is no single best library because each automation category has a standard tool. Use pathlib and shutil for file management, pandas for CSV files and data cleaning, requests with BeautifulSoup for web scraping, pypdf for PDF work, Pillow for images, and smtplib for email. All of them are free, actively maintained in 2026, and installable with pip.

Can beginners write Python automation scripts?

  • Yes. Automation is widely considered the best first project for new programmers because every script solves a problem you personally have. Start with a 10-line file organizer, get it working, then grow it. You will learn Python basics like loops, functions, and file handling faster from one real script than from weeks of abstract exercises.

Do Python automation scripts work on Windows, Mac, and Linux?

  • Yes. Python runs on all three systems, and every script in this guide is cross-platform. The only real difference is scheduling, where Windows uses Task Scheduler while Mac and Linux use cron or launchd.

How do I keep passwords out of my automation scripts?

  • Never write a password directly in your Python code. Store credentials in environment variables or a .env file that stays out of version control, and read them with os.environ as shown in the email script above. For Google services, use app passwords or service accounts instead of your main account password.

How much time can Python automation actually save?

  • It depends on the task, but the reports from working developers are specific and large. Individual cases from the r/learnPython thread include 10 hours per week saved on data entry through OCR, a 6-hour testing routine cut to 15 minutes, and a multi-day PDF sorting job finished in 30 seconds. Even a modest script that saves 20 minutes a day returns roughly 80 hours a year.

Find your coach today.

Browse Related Articles

Sign in
Reviews
Become an expert
For universities
For teams