← All stories

10 Python Automation Scripts That Save Me Hours Every Week

You don't need to be a programmer to automate the boring parts of your computer time. Python comes pre-installed on Mac and Linux, and it's a free download on Windows — and a 10-line script can do in seconds what takes you twenty minutes of clicking.

Here are ten short scripts I actually run every week. All of them use only Python's standard library (no installs needed) except the two marked ones, and each is short enough to read in one glance.

To run any of them: save the code in a file ending in .py, then open a terminal and type python3 script.py (on Windows it's usually just python script.py).

1. Organize your Downloads folder

Sorts every file in Downloads into subfolders by type (pdf, jpg, zip...). Run it once a month and the chaos sorts itself.

from pathlib import Path
import shutil

downloads = Path.home() / "Downloads"  # change if needed
for file in downloads.iterdir():
    if file.is_file():
        ext = file.suffix.lstrip(".").lower() or "no-extension"
        folder = downloads / ext
        folder.mkdir(exist_ok=True)
        shutil.move(str(file), str(folder / file.name))
print("Done.")

2. Bulk-rename files in one shot

Renames every file in a folder to vacation_001.jpg, vacation_002.jpg, and so on. Perfect for photo dumps and scanned documents. Try it on a copy first.

from pathlib import Path

folder = Path("photos")  # change to your folder
count = 0
for file in sorted(folder.iterdir()):
    if file.is_file():
        count += 1
        file.rename(folder / f"vacation_{count:03d}{file.suffix}")
print(f"Renamed {count} files.")

3. Merge multiple CSVs into one

Combines every CSV in the current folder into merged.csv with a single header row. Assumes all files share the same column headers.

import csv, glob

with open("merged.csv", "w", newline="") as out:
    writer = None
    for path in sorted(glob.glob("*.csv")):
        if path == "merged.csv":
            continue
        with open(path, newline="") as f:
            reader = csv.DictReader(f)
            if writer is None:
                writer = csv.DictWriter(out, fieldnames=reader.fieldnames)
                writer.writeheader()
            writer.writerows(reader)
print("Merged into merged.csv")

4. Find duplicate files by content

Computes an MD5 hash — a digital fingerprint — of every file and lists ones with identical content, even if the filenames differ. Review the list before deleting anything.

import hashlib
from pathlib import Path

def file_hash(path):
    h = hashlib.md5()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(8192), b""):
            h.update(chunk)
    return h.hexdigest()

seen = {}
for file in Path(".").rglob("*"):
    if file.is_file():
        seen.setdefault(file_hash(file), []).append(str(file))

for files in seen.values():
    if len(files) > 1:
        print("Duplicates:", *files, sep="\n  ")

5. Timestamped folder backup

Copies a folder into backups/ with the date and time in the name. One run, one dated snapshot, zero thinking.

import shutil
from datetime import datetime
from pathlib import Path

source = Path("Documents")  # folder to back up
stamp = datetime.now().strftime("%Y-%m-%d_%H-%M")
dest = Path("backups") / f"{source.name}_{stamp}"
shutil.copytree(source, dest)
print("Backed up to", dest)

6. Website uptime checker

Pings a list of websites and prints UP or DOWN for each. Point it at your blog, your portfolio, or your side project.

import urllib.request

sites = ["https://google.com", "https://github.com", "https://example.com"]
for url in sites:
    try:
        code = urllib.request.urlopen(url, timeout=10).status
        print(f"UP   {url} ({code})")
    except Exception as e:
        print(f"DOWN {url} ({type(e).__name__})")

7. Scan a log file for errors

Reads a log file and pulls out every line mentioning error, exception, traceback, or failed. Much faster than scrolling through 10,000 lines by hand.

from pathlib import Path

log = Path("app.log")  # change to your log file
keywords = ("error", "exception", "traceback", "failed")
hits = [line.rstrip() for line in log.read_text(errors="replace").splitlines()
        if any(k in line.lower() for k in keywords)]
print(f"{len(hits)} problems found:")
print("\n".join(hits[:50]))

8. Batch-convert images to JPEG

Needs one install: run pip install pillow first. Converts every PNG in a folder to JPEG at 90% quality — handy before uploading images to a blog.

# pip install pillow
from pathlib import Path
from PIL import Image

for src in Path("images").glob("*.png"):
    img = Image.open(src).convert("RGB")
    img.save(src.with_suffix(".jpg"), quality=90)
print("Converted.")

9. Rename photos by date taken

Needs one install: run pip install pillow first. Reads each photo's EXIF data — metadata your camera embeds in the file — and renames it to the date it was taken, like 2024-05-01_10-30-00.jpg. Photos with no date are skipped.

# pip install pillow
from pathlib import Path
from PIL import Image

for photo in Path("photos").glob("*.jpg"):
    exif = Image.open(photo).getexif()
    raw = exif.get(36867)  # DateTimeOriginal
    if raw:
        stamp = raw.replace(":", "-").replace(" ", "_")
        photo.rename(photo.parent / f"{stamp}{photo.suffix}")
print("Renamed by date taken.")

10. Daily disk-usage report

Prints how much disk space is used and appends the line to disk_report.txt. Schedule it daily and you'll spot a filling drive weeks before it bites you.

import shutil
from datetime import date
from pathlib import Path

drive = Path.home().anchor or "/"
total, used, free = shutil.disk_usage(drive)
gb = 1024 ** 3
line = (f"{date.today()}: {used/gb:.1f} GB used of "
        f"{total/gb:.1f} GB ({free/gb:.1f} GB free)")
print(line)
Path("disk_report.txt").write_text(line + "\n")

Put them on autopilot

Scripts are most powerful when they run themselves. On Mac or Linux, add a line to cron — the built-in task scheduler — like this:

0 9 * * * /usr/bin/python3 /home/you/scripts/backup.py

That runs the backup every day at 9 AM. (Type crontab -e to edit your schedule.) On Windows, open Task Scheduler → Create Basic Task, pick your trigger, and set the action to run python.exe with your script as the argument. Set it once, forget it forever.

Join the discussion

Older →Older Post
Older →Older Post