DEV Community

Joey Umanito
Joey Umanito

Posted on

Python Automation: 5 Tasks You Should Automate Right Now

Stop doing repetitive tasks manually. Python makes it easy to automate your most time-consuming workflows. Here are 5 tasks you can automate today, with complete code examples.

1. Automated Email Reports

Send daily/weekly reports automatically:

import smtplib
import schedule
import time
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from datetime import datetime

def send_report(recipient, subject, body):
    sender = "your_email@gmail.com"
    password = "your_app_password"

    msg = MIMEMultipart()
    msg["From"] = sender
    msg["To"] = recipient
    msg["Subject"] = subject
    msg.attach(MIMEText(body, "html"))

    with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
        server.login(sender, password)
        server.send_message(msg)

    print(f"Report sent to {recipient}")

def generate_daily_report():
    today = datetime.now().strftime("%Y-%m-%d")
    body = f"""
    <h2>Daily Report - {today}</h2>
    <p>Automated report generated by Python.</p>
    <ul>
        <li>Task 1: Complete</li>
        <li>Task 2: In Progress</li>
    </ul>
    """
    send_report("boss@company.com", f"Daily Report {today}", body)

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

while True:
    schedule.run_pending()
    time.sleep(60)
Enter fullscreen mode Exit fullscreen mode

2. Automated File Organization

Sort downloads folder automatically:

import os
import shutil
from pathlib import Path
import schedule

DOWNLOADS = Path.home() / "Downloads"

FILE_CATEGORIES = {
    "Images": [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".svg"],
    "Videos": [".mp4", ".mkv", ".avi", ".mov", ".wmv"],
    "Documents": [".pdf", ".doc", ".docx", ".txt", ".xlsx", ".pptx"],
    "Audio": [".mp3", ".wav", ".flac", ".aac"],
    "Code": [".py", ".js", ".html", ".css", ".json", ".xml"],
    "Archives": [".zip", ".rar", ".tar", ".gz", ".7z"]
}

def organize_downloads():
    for file_path in DOWNLOADS.iterdir():
        if file_path.is_file():
            extension = file_path.suffix.lower()

            category = "Other"
            for cat, extensions in FILE_CATEGORIES.items():
                if extension in extensions:
                    category = cat
                    break

            target_folder = DOWNLOADS / category
            target_folder.mkdir(exist_ok=True)

            shutil.move(str(file_path), str(target_folder / file_path.name))
            print(f"Moved {file_path.name} to {category}/")

schedule.every().hour.do(organize_downloads)

while True:
    schedule.run_pending()
    time.sleep(60)
Enter fullscreen mode Exit fullscreen mode

3. Web Scraping for Price Tracking

Track product prices and get alerts:

import requests
from bs4 import BeautifulSoup
import smtplib
import schedule

def check_price(url, target_price, product_name):
    headers = {"User-Agent": "Mozilla/5.0"}
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.content, "html.parser")

    # Adjust selector for your target website
    price_element = soup.find("span", {"class": "price"})
    if price_element:
        price_text = price_element.get_text().replace("$", "").replace(",", "").strip()
        current_price = float(price_text)

        print(f"{product_name}: Current ${current_price}, Target ${target_price}")

        if current_price <= target_price:
            send_alert(product_name, current_price, url)

def send_alert(product, price, url):
    print(f"PRICE DROP ALERT: {product} is now ${price}! Buy at: {url}")
    # Add email notification here

# Track multiple products
products = [
    {"url": "https://example.com/product1", "target": 50, "name": "Laptop Stand"},
]

for product in products:
    schedule.every(6).hours.do(
        check_price, product["url"], product["target"], product["name"]
    )

while True:
    schedule.run_pending()
Enter fullscreen mode Exit fullscreen mode

4. Social Media Auto-Posting

Schedule posts across platforms:

import tweepy
import schedule
import time
from datetime import datetime

def create_twitter_client():
    auth = tweepy.OAuthHandler("API_KEY", "API_SECRET")
    auth.set_access_token("ACCESS_TOKEN", "ACCESS_SECRET")
    return tweepy.API(auth)

CONTENT_CALENDAR = [
    {"time": "09:00", "text": "Good morning! Here is your Python tip of the day: Use list comprehensions for cleaner code! #Python #Programming"},
    {"time": "13:00", "text": "Afternoon reminder: Take breaks from coding every 45 minutes. Your brain needs rest to work better! #DevLife"},
    {"time": "18:00", "text": "Evening reading recommendation: Check out the Python documentation for new features in 3.12! #Python"},
]

twitter = create_twitter_client()

for post in CONTENT_CALENDAR:
    schedule.every().day.at(post["time"]).do(
        lambda text=post["text"]: twitter.update_status(text)
    )

while True:
    schedule.run_pending()
    time.sleep(60)
Enter fullscreen mode Exit fullscreen mode

5. Database Backup Automation

Never lose your data:

import subprocess
import os
import schedule
from datetime import datetime

BACKUP_DIR = "/backups"
DB_NAME = "myapp_db"
DB_USER = "postgres"

def backup_database():
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    backup_file = f"{BACKUP_DIR}/{DB_NAME}_{timestamp}.sql"

    os.makedirs(BACKUP_DIR, exist_ok=True)

    command = f"pg_dump -U {DB_USER} {DB_NAME} > {backup_file}"
    result = subprocess.run(command, shell=True, capture_output=True)

    if result.returncode == 0:
        print(f"Backup successful: {backup_file}")
        cleanup_old_backups()
    else:
        print(f"Backup failed: {result.stderr.decode()}")

def cleanup_old_backups():
    backups = sorted(Path(BACKUP_DIR).glob("*.sql"))
    if len(backups) > 7:
        for old_backup in backups[:-7]:
            old_backup.unlink()
            print(f"Deleted old backup: {old_backup}")

schedule.every().day.at("02:00").do(backup_database)

while True:
    schedule.run_pending()
    time.sleep(3600)
Enter fullscreen mode Exit fullscreen mode

Running Your Automation Scripts

Keep scripts running with PM2:

npm install -g pm2
pm2 start automation.py --interpreter python3
pm2 save
pm2 startup
Enter fullscreen mode Exit fullscreen mode

Want Custom Automation Built For You?

Need a specific workflow automated for your business? Whether it is:

  • Report generation and distribution
  • Data processing pipelines
  • Social media management
  • File organization systems

I can build it for you professionally:


What task do you want to automate first? Share in the comments!

Top comments (0)