Automate Your Workflow with Python Scripts

Photo by Godfrey Atima on Pexels
Automate Your Workflow with Python Scripts
Python has become the default language for workflow automation because of its readability, extensive standard library, and rich ecosystem of third-party packages. Whether you need to process files, scrape websites, send emails, or orchestrate cloud services, Python can handle it. In this article, we explore practical automation scripts that eliminate repetitive tasks and free up your time for meaningful development work. Each script is designed to be a standalone solution that you can adapt to your specific needs with minimal modification.
Why Choose Python for Automation?
Python’s philosophy of readability and batteries-included makes it uniquely suited for automation. Unlike bash, Python handles complex data structures gracefully with dictionaries, lists, and sets. Unlike compiled languages, Python scripts can be edited and run instantly without a build step, making the iteration cycle fast. The result is faster development and easier maintenance for automation pipelines that need to evolve as your requirements change.
- Cross-platform — runs identically on Windows, macOS, and Linux
- Vast standard library — os, shutil, glob, re, json, csv out of the box without any pip install
- Third-party ecosystem — requests, beautifulsoup4, pandas, openpyxl for specialized tasks
- Easy scheduling with cron, Windows Task Scheduler, or the schedule library
- Strong error handling with try/except blocks for production reliability
1. Automated File Organizer
This script scans a download directory and moves files into subfolders based on their extensions. Images go to Pictures, documents to Documents, archives to Archives, and so on. It handles duplicate filenames gracefully by appending timestamps, and it skips files that are currently in use to prevent errors. The script runs silently in the background and only reports what it moved, making it ideal for cron-based scheduling.
import os
import shutil
from pathlib import Path
from datetime import datetime
DOWNLOADS = Path.home() / "Downloads"
CATEGORIES = {
"Images": [".jpg", ".jpeg", ".png", ".gif", ".webp"],
"Documents": [".pdf", ".docx", ".txt", ".md"],
"Archives": [".zip", ".tar.gz", ".rar", ".7z"],
"Code": [".py", ".js", ".ts", ".html", ".css"],
}
for file in DOWNLOADS.iterdir():
if file.is_file():
for folder, extensions in CATEGORIES.items():
if file.suffix.lower() in extensions:
target = DOWNLOADS / folder / file.name
target.parent.mkdir(exist_ok=True)
if target.exists():
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
target = DOWNLOADS / folder / f"{file.stem}_{timestamp}{file.suffix}"
shutil.move(str(file), str(target))
print(f"Moved: {file.name} -> {folder}/")
break
2. CSV to Excel Converter with Formatting
Data analysts frequently need to convert CSV exports into formatted Excel reports for stakeholders who prefer spreadsheets. This script reads a CSV file, auto-adjusts column widths, applies header styling with a professional color scheme, and saves as .xlsx with multiple sheets if needed. It also handles encoding detection so that CSV files with special characters are processed correctly.
3. Web Scraper for Price Monitoring
E-commerce sellers and marketers need competitive pricing data to adjust their strategies. This script scrapes product pages, extracts prices and availability, and saves the data to a timestamped JSON file. Run it hourly to track price changes over time and identify trends. The script includes polite scraping practices with configurable delays to avoid overwhelming target servers.
Key Features
- Respects robots.txt with
urllib.robotparserto comply with site policies - Randomized user-agent rotation to avoid detection and blocking
- Configurable delay between requests to be a good citizen of the web
- Outputs structured JSON for downstream analysis and visualization
- Handles connection errors gracefully with automatic retries
4. Automated Email Reporter
Generate and send daily or weekly reports via email without manual intervention. This script compiles data from multiple sources, renders an HTML email template with inline styling, and sends it through SMTP with optional file attachments. The template is fully customizable with your branding colors and logo.
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
msg = MIMEMultipart()
msg["Subject"] = f"Daily Report - {datetime.now().strftime('%Y-%m-%d')}"
msg["From"] = "[email protected]"
msg["To"] = "[email protected]"
html = """
Daily Summary
All systems operational.
Metric Value
"""
msg.attach(MIMEText(html, "html"))
with smtplib.SMTP("smtp.example.com", 587) as server:
server.starttls()
server.login("user", "password")
server.send_message(msg)
print("Report sent successfully.")
Use environment variables for SMTP credentials instead of hardcoding them as shown above. Store sensitive values in a .env file or your CI/CD secrets manager.
5. Database Backup and Sync
A Python script that offers more flexibility than bash equivalents. It supports multiple database types including PostgreSQL, MySQL, and SQLite, runs parallel backups of multiple databases for efficiency, optionally uploads to S3 or Google Cloud Storage, and writes detailed logs to a file for auditing. The script also sends a notification on failure so you never discover a missed backup days later.
6. API Rate Limiter and Caching Proxy
When working with third-party APIs, rate limits and latency are constant concerns. This script implements a local caching proxy that stores API responses and respects rate limits with a token bucket algorithm, reducing both costs and latency significantly. Responses within the cache TTL are served instantly without making a network request, and the rate limiter ensures you never exceed your API quota.
Setting Up Scheduled Execution
Automation scripts are most valuable when they run on a schedule. Here is how to set up cron jobs on Linux:
# Run file organizer every hour
0 * * * * /usr/bin/python3 /home/user/organize.py >> /var/log/organizer.log 2>&1
# Run email report every weekday at 8 AM
0 8 * * 1-5 /usr/bin/python3 /home/user/send_report.py >> /var/log/reporter.log 2>&1
# Monitor prices every 30 minutes
*/30 * * * * /usr/bin/python3 /home/user/price_monitor.py
On Windows, use Task Scheduler. On macOS, use launchd or cron. Always redirect output to a log file so you can review execution history and troubleshoot issues.
Best Practices for Python Automation
- Use virtual environments (venv) to isolate dependencies per project and avoid version conflicts
- Log all actions with the logging module instead of print statements for better control over output levels
- Handle exceptions gracefully with specific exception types — never use bare except clauses that hide bugs
- Use environment variables in a .env file for credentials and configuration, never hardcode secrets
- Write unit tests for critical automation logic using pytest to catch regressions early
- Include a dry-run mode for destructive operations like file moves or deletions
- Version-control your scripts even if they run locally only — you will thank yourself later
Download the Script Collection
All six Python automation scripts are available for free download on freefile.store. Each script includes a requirements.txt file, configuration examples in YAML format, comprehensive docstrings, and a quick-start guide. Streamline your workflow today and stop wasting time on tasks that a computer can do for you in milliseconds.