Python automation scripts changed my workday rhythm. A few months back, I had a stack of spreadsheets, a pile of scanned invoices, and a boss who wanted “one neat report by 5 PM.” I brewed a questionable espresso, opened VS Code, and stitched together a tiny toolkit. Two hours later, everything clicked—files merged, PDFs renamed, images shrunk, and a neat contract set printed. Since that week, I’ve kept a folder of bite-size utilities ready to fire. This guide is that folder, cleaned up for you.
We’ll mirror a simple structure for each task: the scenario, a clean script, and the thinking behind it. I’ll offer light upgrades so you can adapt fast. And because these Python automation scripts are meant for daily life, every example avoids exotic dependencies, sticks to human-readable code, and plays nicely across Windows, macOS, and Linux.
Heads up: I’ll sprinkle links to docs and a couple of related guides for deeper rabbit holes. Nothing fancy. Just what saves time.
1) Merge monthly Excel files into one master workbook
Scenario
Finance drops ten Excel files in a folder named “Reports_This_Month.” You need one consolidated sheet, deduped, with clean types. This is where Python automation scripts shine: repeatable, boring, and blissfully fast.
The script
# pip install pandas openpyxl from pathlib import Path import pandas as pd
src = Path("D:/reports") # or Path.home() / "Documents" / "reports"
files = sorted(src.glob("*.xlsx"))
dfs = []
for f in files:
try:
df = pd.read_excel(f)
df["__source"] = f.name
dfs.append(df)
except Exception as e:
print(f"Skip {f.name}: {e}")
out = (pd.concat(dfs, ignore_index=True)
.drop_duplicates()
.convert_dtypes())
out.to_excel("master_report.xlsx", index=False)
print("Saved master_report.xlsx")
Why it works
Excel excels at presentation; pandas
excels at structure. This play corrals scattered sheets into one reliable dataset. The __source
column makes audits easy when someone asks, “Where did row 12 come from?” It’s one of my go-to Python automation scripts because it replaces hours of manual copy-paste with one command.
Upgrades
- Type expectations: build a schema dict and call
astype()
to force critical columns into the right dtypes. - Filters: toss out summary tabs by checking for required headers before appending.
- Docs for later: pandas official docs and pathlib are your best friends when these grow up.
2) Batch-rename scanned invoice PDFs using code + amount
Scenario
Scans arrive as scan0001.pdf
to scan0099.pdf
. Accounting wants filenames like InvoiceCode_Amount.pdf
. Manual renaming is a trap. Another win for small Python automation scripts.
The script
# pip install pymupdf import re, os, sys import fitz # PyMuPDF from pathlib import Path
src = Path("invoices")
pat_code = re.compile(r"(?:Invoice\sCode|invocenumber)[::]?\s([0-9A-Za-z-]+)")
pat_amt = re.compile(r"([¥$]?\s*\d+(?:,\d{3})*(?:.\d{2}))")
for f in src.glob("*.pdf"):
try:
with fitz.open(f) as doc:
text = "\n".join(page.get_text() for page in doc)
code = pat_code.search(text)
amt = pat_amt.search(text)
if not (code and amt):
print(f"Skip {f.name}: no match")
continue
code_str = code.group(1).replace("/", "-")
amt_str = amt.group(1).replace(" ", "").replace("¥", "CNY").replace("$", "USD")
new = f.with_name(f"{code_str}_{amt_str}.pdf")
if new.exists():
print(f"Skip (exists): {new.name}")
continue
os.rename(f, new)
print("Renamed:", new.name)
except Exception as e:
print("Error:", f.name, e, file=sys.stderr)
Hardening tips
- OCR: if a PDF is an image, run OCR first (e.g., Tesseract) or use the text extraction features in PyMuPDF.
- Regex sanity: log unmatched files to a CSV for manual follow-up; don’t silently drop them.
- Docs: PyMuPDF’s reference is tidy—peek at PyMuPDF docs.
3) Word contract mail-merge from a template
Scenario
HR hands you contract_template.docx
and a spreadsheet with 100 rows. You need 100 personalized contracts with names, amounts, and dates slotted in the right places. This might sound like heavy enterprise software, but small Python automation scripts do the job beautifully.
The script
# pip install python-docx pandas import pandas as pd from docx import Document from pathlib import Path
tpl = Document("contract_template.docx")
rows = pd.read_excel("contract_data.xlsx").to_dict(orient="records")
outdir = Path("out"); outdir.mkdir(exist_ok=True)
placeholders = {"":"company","":"name","":"amount","":"date"}
for row in rows:
doc = Document()
doc._body = tpl._body.element.clone() # start from template body
for p in doc.paragraphs:
for ph, key in placeholders.items():
if ph in p.text:
p.text = p.text.replace(ph, str(row.get(key, "")))
for tbl in doc.tables:
for r in tbl.rows:
for c in r.cells:
for ph, key in placeholders.items():
if ph in c.text:
c.text = c.text.replace(ph, str(row.get(key, "")))
doc.save(outdir / f"Contract{row['name']}.docx")
Notes and upgrades
- Make placeholders obvious (e.g.,
<Amount>
) and avoid accidental partial matches. - If you need PDFs, print to PDF via Office automation or a cross-platform CLI.
- Docs: python-docx docs are short and practical.
4) 9:25 AM team ping: auto check-in reminder to DingTalk
Scenario
Someone always forgets to “tap the button.” You’re not here to play hall monitor. One of the simplest Python automation scripts keeps your chat room on schedule with a small webhook post.
The script
# pip install requests import requests, datetime
WEBHOOK = "https://oapi.dingtalk.com/robot/send?access_token=REDACTED
"
def remind():
now = datetime.datetime.now().strftime("%H:%M")
text = f"{now} — time to check in!"
payload = {"msgtype":"text","text":{"content":text}}
requests.post(WEBHOOK, json=payload, timeout=5)
if name == "main":
remind()
Scheduling
- Windows: Task Scheduler → Create Task → Trigger daily at 09:25 → Action:
python remind.py
. - macOS/Linux:
crontab -e
→25 9 * * * /usr/bin/python3 /path/remind.py
. - Rotate tokens regularly; store secrets in env vars.
5) Compress large photos before emailing
Scenario
Design sends you a folder of beautiful, 20-megabyte JPEGs. Your email server disagrees. A tiny compressor script trims images to sane sizes while keeping quality. This is another everyday slot for Python automation scripts.
The script
# pip install pillow from pathlib import Path from PIL import Image, ImageOps
src = Path("photos")
dst = Path("photos_small"); dst.mkdir(exist_ok=True)
for f in src.rglob("*.jpg"):
try:
im = Image.open(f)
im = ImageOps.exif_transpose(im) # respect orientation
im.thumbnail((1920, 1080)) # cap longest edge
out = dst / f"{f.stem}_small.jpg"
im.save(out, optimize=True, quality=85)
print("Saved", out.name)
except Exception as e:
print("Skip", f, e)
Tips
- Prefer
.thumbnail()
for in-place proportional scaling. - Use
optimize=True
and tweakquality
until the trade-off fits. - Docs: Pillow’s quickstart is here—Pillow docs.
6) Auto-tidy your downloads folder by file type
Scenario
“Downloads” is chaos. Screenshots, ZIPs, slides, and code snippets all in one pile. This is where Python automation scripts tame entropy by sorting files into tidy subfolders.
The script
import shutil from pathlib import Path
DOWN = Path.home() / "Downloads"
MAP = {
"xlsx|xls|csv": "Spreadsheets",
"pdf|docx|pptx": "Documents",
"jpg|jpeg|png|webp": "Images",
"zip|rar|7z": "Archives",
"py|js|ts|java": "Code"
}
for f in DOWN.iterdir():
if not f.is_file():
continue
ext = f.suffix.lower().lstrip(".")
for group, folder in MAP.items():
if ext in group.split("|"):
target = DOWN / folder
target.mkdir(exist_ok=True)
shutil.move(str(f), str(target / f.name))
print("Moved", f.name, "→", folder)
break
Why it helps
Every minute you don’t spend hunting for files is a minute you can fix the real problem. If you’re locking down Windows fleets, pair this with a clean security baseline—our practical walkthrough on Microsoft Defender is a great companion when you standardize endpoints.
7) Generate a Wi-Fi QR code for guests
Scenario
Visitors keep asking for the SSID and password. Print a QR code, tape it to the wall, and enjoy the silence. This is where Python automation scripts add delight to mundane office life.
The script
# pip install qrcode[pil] import qrcode
ssid = "Company-WiFi"
pwd = "S3cure-2025!"
auth = "WPA" # or "WEP" / "nopass"
text = f"WIFI:T:{auth};S:{ssid};P:{pwd};;"
img = qrcode.make(text)
img.save("wifi.png")
print("Saved wifi.png")
Practical notes
- Use mixed-case passwords and symbols; rotate regularly.
- Print on matte paper—glare makes scanning harder in bright lobbies.
- Curious about radio generations and why your guest network sometimes lags? Our deep dive on WiFi Generations pairs nicely with this step.
- If you roll your own portal later, stash SSIDs as variables so you can generate multiple QR codes at once.
8) One-click cleanup for desktop screenshots
Scenario
Win+Shift+S (or macOS Shift-Cmd-4) leaves your desktop looking like a sticker bomb. This is the lightest of all Python automation scripts, and maybe the one I run the most.
The script
from pathlib import Path import shutil, datetime
desk = Path.home() / "Desktop"
stamp = datetime.datetime.now().strftime("%Y%m%d")
target = desk / f"Screenshots_{stamp}"
target.mkdir(exist_ok=True)
for f in list(desk.glob(".png")) + list(desk.glob(".jpg")):
shutil.move(str(f), str(target / f.name))
print("Moved screenshots to", target)
Quality-of-life tweaks
- Filter by prefix (
Screenshot
or locale-specific name) if your desktop has other images. - Set a weekly cron/Task Scheduler run and forget it.
- Archive older folders into a monthly ZIP to save space.
Frequently asked questions (from real use)
How do I structure my toolbox?
Keep a top-level folder like ~/tools/automation
and split by theme (excel
, pdf
, images
, chat
, desktop
). A README.md
with a one-line summary for each script will save future-you. These Python automation scripts are tiny; the real magic is how quickly you can find and run them.
How do I run them safely on shared machines?
Create a virtual environment per cluster of tasks. Pin versions in requirements.txt
. Avoid hard-coding credentials (env vars or a secrets manager instead). With that hygiene in place, Python automation scripts become a low-risk, high-reward habit.
What if I want a single “launcher”?
Write a tiny CLI wrapper that calls each task via subcommands. It’s neat, discoverable, and turns eight standalone utilities into one cohesive toolkit.
# pip install typer rich import typer, subprocess, sys from rich import print app = typer.Typer(help="Office Helpers: small Python automation scripts") @app.command() def excel(path: str = "D:/reports"): subprocess.run([sys.executable, "merge_excel.py", path]) @app.command() def invoices(): subprocess.run([sys.executable, "rename_invoices.py"]) @app.command() def wifi(ssid: str, pwd: str, auth: str = "WPA"): subprocess.run([sys.executable, "wifi_qr.py", ssid, pwd, auth]) if __name__ == "__main__": app()
A quick personal note to wrap it up
One Friday at 4:43 PM I got a “quick ask” that was neither quick nor an ask. I closed chat, ran the consolidator, fired the PDF renamer, and launched the image compressor while I packed my bag. Everything finished before the elevator hit the lobby. That’s what these Python automation scripts buy you: calm. You’ll still have hard problems, but the boring ones vanish.
Keep iterating. Add logging where it hurts, memoize where it’s slow, and don’t be afraid to throw away a script that no longer earns its place. If you’ve made it this far, you’ve already joined the quiet club of people who automate their day and look strangely unbothered.
Resources for deeper tinkering
And if you’re hardening endpoints, you might also enjoy: Microsoft Defender: 15 Unbeatable Reasons This Free Suite Smokes Paid Antivirus (security hardening vibes). For network planning homework, here’s our readable take on generations: WiFi Generations Showdown.
PS: If you want more ideas like these Python automation scripts, drop a note—happy to add an OCR pipeline, CSV validators, or a one-stop backup job next.