DEV Community

Brad
Brad

Posted on

5 Python Scripts That Eliminated My Most Hated Business Tasks

Every Sunday I used to spend 2 hours on business admin. Now Python handles it automatically.

Here are 5 scripts that made the biggest difference:

1. File Organizer (Runs Daily via Cron)

import shutil
from pathlib import Path
from datetime import datetime

RULES = {
    "invoices": [".pdf"],
    "images": [".jpg", ".jpeg", ".png"],
    "documents": [".doc", ".docx", ".txt"],
    "data": [".csv", ".xlsx"]
}

def organize(source, target):
    moved = 0
    for file in Path(source).iterdir():
        if not file.is_file():
            continue
        for folder, exts in RULES.items():
            if file.suffix.lower() in exts:
                dest = Path(target) / folder
                dest.mkdir(exist_ok=True)
                final = dest / file.name
                if final.exists():
                    ts = datetime.now().strftime("%Y%m%d_%H%M%S")
                    final = dest / (file.stem + "_" + ts + file.suffix)
                shutil.move(str(file), str(final))
                moved += 1
                break
    print("Organized " + str(moved) + " files")
    return moved

# Cron: 0 9 * * * python organize.py
organize("/Users/you/Downloads", "/Users/you/Organized")
Enter fullscreen mode Exit fullscreen mode

2. Weekly Summary Email (Sent Mondays at 9am)

import csv, smtplib
from email.mime.text import MIMEText
from datetime import datetime, timedelta

def weekly_summary(data_file, to_email, from_email, smtp_pass):
    week_ago = datetime.now() - timedelta(days=7)
    revenue = 0
    expenses = 0
    transactions = 0

    with open(data_file) as f:
        for row in csv.DictReader(f):
            try:
                row_date = datetime.strptime(row["date"], "%Y-%m-%d")
                if row_date >= week_ago:
                    amount = float(row["amount"])
                    if row["type"] == "revenue":
                        revenue += amount
                    else:
                        expenses += amount
                    transactions += 1
            except:
                pass

    body = "Weekly Summary
"
    body += "Revenue: $" + str(round(revenue, 2)) + "
"
    body += "Expenses: $" + str(round(expenses, 2)) + "
"
    body += "Net: $" + str(round(revenue - expenses, 2)) + "
"
    body += "Transactions: " + str(transactions)

    msg = MIMEText(body)
    msg["Subject"] = "Weekly Business Summary"
    msg["From"] = from_email
    msg["To"] = to_email

    with smtplib.SMTP_SSL("smtp.gmail.com", 465) as s:
        s.login(from_email, smtp_pass)
        s.send_message(msg)
    print("Summary sent!")
Enter fullscreen mode Exit fullscreen mode

3. Price Monitor (Get Alerts When Competitors Change Prices)

import requests, json
from bs4 import BeautifulSoup

def check_price(url, css_selector):
    import re
    resp = requests.get(url, headers={"User-Agent": "Mozilla/5.0"}, timeout=10)
    soup = BeautifulSoup(resp.text, "html.parser")
    elem = soup.select_one(css_selector)
    if elem:
        nums = re.findall(r"[\d.]+", elem.get_text())
        return float(nums[0]) if nums else None
    return None

def monitor_and_alert(products, cache="prices.json"):
    try:
        cached = json.load(open(cache))
    except:
        cached = {}

    for p in products:
        current = check_price(p["url"], p["selector"])
        previous = cached.get(p["name"])

        if previous and current and abs(current - previous) > 0.01:
            pct = ((current - previous) / previous) * 100
            print(p["name"] + " changed: $" + str(previous) + " -> $" + str(current) + " (" + str(round(pct,1)) + "%)")

        if current:
            cached[p["name"]] = current

    json.dump(cached, open(cache, "w"))
Enter fullscreen mode Exit fullscreen mode

4. Auto-Backup to Cloud Storage

import zipfile, os
from datetime import datetime
from pathlib import Path

def backup_to_zip(dirs_to_backup, output_dir="backups"):
    ts = datetime.now().strftime("%Y%m%d_%H%M%S")
    zip_name = output_dir + "/backup_" + ts + ".zip"

    Path(output_dir).mkdir(exist_ok=True)

    with zipfile.ZipFile(zip_name, "w", zipfile.ZIP_DEFLATED) as zf:
        for dir_path in dirs_to_backup:
            for file_path in Path(dir_path).rglob("*"):
                if file_path.is_file():
                    zf.write(file_path, file_path.relative_to(Path(dir_path).parent))

    size = os.path.getsize(zip_name) / 1024 / 1024
    print("Backup created: " + zip_name + " (" + str(round(size, 1)) + " MB)")
    return zip_name

# Cron: 0 2 * * * python backup.py
backup_to_zip(["/Users/you/Documents", "/Users/you/Projects"])
Enter fullscreen mode Exit fullscreen mode

5. Lead Tracker (CSV + Auto Email)

import csv, smtplib
from email.mime.text import MIMEText
from datetime import datetime
from pathlib import Path

def add_lead(name, email, source, notes="", file="leads.csv"):
    new_file = not Path(file).exists()
    with open(file, "a", newline="") as f:
        w = csv.writer(f)
        if new_file:
            w.writerow(["Name", "Email", "Source", "Notes", "Date", "Status"])
        w.writerow([name, email, source, notes, datetime.now().date(), "new"])
    print("Lead added: " + name)

def get_new_leads(file="leads.csv"):
    leads = []
    if not Path(file).exists():
        return leads
    with open(file) as f:
        for row in csv.DictReader(f):
            if row["Status"] == "new":
                leads.append(row)
    return leads

# Add leads as they come in
add_lead("Jane Smith", "jane@example.com", "website", "Interested in automation package")
print(str(len(get_new_leads())) + " new leads waiting for follow-up")
Enter fullscreen mode Exit fullscreen mode

The Full Toolkit

These are 5 of 12 scripts in the Python Business Automation Toolkit (9).

All 12 scripts are documented and ready to run. The full package covers everything from invoice generation to email automation to business dashboards.


Which task here would save you the most time? Drop a comment.

Top comments (0)