10 Python Automation Scripts Every Developer Needs
Ten practical Python automation scripts for developers, with a safe script template and working code for file organizing, rotating backups and disk alerts.

On a Monday morning I counted the files in my Downloads folder: 1,400. Somewhere in there was the PDF a client had asked for twice. I wrote a 30-line script that sorted the folder by file type, ran it, and then spent ten minutes making sure it could not overwrite anything, because the first version happily would have. That second step is what separates a useful automation from a liability.
Here are the ten scripts I reach for most, a template that makes any of them safer, and working code for the first three. For heavier data work see Python Automation for the Modern Engineer, and for secrets, log triage and license checks see Python Ops Automation.
Quick takeaways
- Start every script from the same template: dry-run by default, logging, and an honest exit code.
- Scripts that move or delete things must never overwrite; check the destination first.
- Schedule with cron or Task Scheduler, send output to a log, and alert on non-zero exit.
- Keep configuration in environment variables or a config file, not in the code.
- Automate the task you have repeated three times, not the one you might repeat someday.
What should every automation script start from?
This skeleton gives each script the same behavior: nothing changes unless you pass --apply, errors are logged with a traceback, and the exit code tells a scheduler whether anything went wrong.
#!/usr/bin/env python3
"""Template for small automation scripts."""
import argparse
import logging
import sys
log = logging.getLogger("automation")
def parse_args(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--apply", action="store_true", help="make changes (default: dry run)")
parser.add_argument("-v", "--verbose", action="store_true")
return parser.parse_args(argv)
def run(apply: bool) -> int:
"""Do the work. Return the number of problems found; 0 means success."""
return 0
def main(argv=None) -> int:
args = parse_args(argv)
logging.basicConfig(
level=logging.DEBUG if args.verbose else logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
)
try:
problems = run(args.apply)
except Exception:
log.exception("unhandled error")
return 2
return 1 if problems else 0
if __name__ == "__main__":
sys.exit(main())
Every script below plugs into run(). For the reasoning behind logging and failing loudly, see Error Handling Patterns.
1. How do I organize files by type automatically?
The file organizer sorts a folder into subfolders by extension. The important detail is the collision check:
import logging
import shutil
from pathlib import Path
log = logging.getLogger("automation")
CATEGORIES = {
"images": {".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg"},
"documents": {".pdf", ".docx", ".txt", ".md", ".xlsx"},
"code": {".py", ".js", ".ts", ".go", ".json", ".yaml", ".yml"},
"archives": {".zip", ".tar", ".gz", ".7z"},
}
def category_for(path: Path):
for name, extensions in CATEGORIES.items():
if path.suffix.lower() in extensions:
return name
return None
def organize(folder: Path, apply: bool) -> int:
collisions = 0
for item in sorted(folder.iterdir()):
category = category_for(item) if item.is_file() else None
if category is None:
continue
target = folder / category / item.name
if target.exists():
log.warning("skip %s: %s already exists", item.name, target)
collisions += 1
continue
log.info("%s %s -> %s/", "move" if apply else "would move", item.name, category)
if apply:
target.parent.mkdir(exist_ok=True)
shutil.move(str(item), target)
return collisions
Run it without --apply first and read the list. Files with unknown extensions stay where they are.
2. How do I back up a directory with rotation?
Create a timestamped archive, then delete all but the newest few. The archive is written before anything is deleted, so a failed run never leaves you with fewer backups:
import tarfile
from datetime import datetime
from pathlib import Path
def backup(source: Path, dest: Path, keep: int = 7) -> Path:
dest.mkdir(parents=True, exist_ok=True)
stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
archive = dest / f"{source.name}-{stamp}.tar.gz"
with tarfile.open(archive, "w:gz") as tar:
tar.add(source, arcname=source.name)
for old in sorted(dest.glob(f"{source.name}-*.tar.gz"))[:-keep]:
old.unlink()
return archive
Timestamps in the filename sort lexicographically, so sorting by name also sorts by age. Copy the archives to a second location, ideally another machine or a storage bucket; a backup on the same disk protects against typos, not hardware failure.
3. How do I get an alert before a disk fills up?
import shutil
def disk_alerts(paths: list[str], threshold: float = 0.85) -> list[str]:
alerts = []
for path in paths:
usage = shutil.disk_usage(path)
used = usage.used / usage.total
if used >= threshold:
alerts.append(f"{path} is {used:.0%} full")
return alerts
Return the alerts from run() as the problem count, and the exit code does the rest.
What are the other seven scripts?
- Log analyzer: extract errors and group them by message; the grouping approach is in the Python Ops Automation post linked above.
- API health checker: call a list of endpoints concurrently with timeouts; an async example is in the Modern Engineer post.
- Database backup:
pg_dumpormysqldumpwith compression and an upload, using the same rotation idea as script 2. - Email reporter: build a summary from your data and send it with
smtplibor your provider's API. - Git repository cleanup: list merged branches and delete them after confirmation.
- Web scraper template: one function for fetching with rate limiting and retries, one for parsing, one for export. Check the site's terms and robots.txt first.
- Environment setup: a script that installs tools, creates the virtual environment and copies a sample
.env, so a new teammate is productive in minutes.
How do I run these on a schedule?
Use cron on Linux and macOS, or Task Scheduler on Windows. Write output to a log and alert when the script fails:
# crontab -e (define ALERT_WEBHOOK at the top of the crontab)
15 2 * * * /usr/bin/python3 /opt/scripts/backup.py --apply >> /var/log/backup.log 2>&1 || curl -fsS -X POST "$ALERT_WEBHOOK" -d "backup failed"
Cron has a minimal environment, so use absolute paths for the interpreter and the script. For when cron is enough and when it is not, read Cron Isn't Dead.
What should I do next?
Open your shell history and find the command or manual task you ran three or more times last month. Copy the template, implement that one task in run(), and run it in dry-run mode for a week next to your manual process. When the output matches what you would have done by hand, add --apply and a cron entry. Write a short test for the function that decides what to move or delete; that test is what lets you trust the script months later.
Uğur Kaval
AI/ML Engineer & Full Stack Developer specializing in building innovative solutions with modern technologies. Passionate about automation, machine learning, and web development.


