Python is one of the easiest ways to automate repetitive computer work. With the built-in pathlib and shutil modules, a short script can sort a messy folder, rename hundreds of files, archive old ones, make backups, and combine reports, and a scheduler can run it every day without you.

Everyone has tasks that eat a few minutes every day: cleaning up the Downloads folder, renaming scanned files, zipping last month’s documents, merging the weekly CSV exports from three systems. None of them is hard, but together they add up to hours. These are perfect jobs for Python: the logic is simple, the standard library already has the tools, and once a script works, it does the job the same way every time.

This guide builds a set of small, practical automation scripts, all using only Python’s standard library, so there’s nothing to install. Every example was run on a sample folder, and the output shown is real. If you’re new to Python, start with Python Basics: Files and Exceptions.

Before You Automate: Work on a Copy

Scripts that move, rename, and delete files can do a lot of damage quickly. Three rules keep you safe:

  1. Test on a copy of the folder first, never on the real thing.
  2. Start with a “dry run” that only prints what it would do.
  3. Move instead of delete whenever you can, so mistakes can be undone. And keep backups.

The examples use a sample Downloads folder with eight files of different types.

Listing Files With pathlib

pathlib represents file paths as objects with useful properties, which is clearer than working with strings:

from pathlib import Path

downloads = Path("Downloads")
for path in sorted(downloads.iterdir()):
    if path.is_file():
        print(f"{path.name:<22} {path.suffix:<6} {path.stat().st_size:>6} bytes")
budget.xlsx            .xlsx     800 bytes
data.csv               .csv      600 bytes
invoice-march.pdf      .pdf     1200 bytes
logo.png               .png     2500 bytes
notes.txt              .txt      120 bytes
report final (2).pdf   .pdf     3400 bytes
setup.exe              .exe     9000 bytes
team photo.JPG         .JPG     5300 bytes

iterdir() lists a folder’s contents, .name is the file name, .suffix is the extension, and .stat().st_size is the size in bytes. pathlib works the same on Windows, macOS, and Linux, so you don’t need to worry about \ versus /.

To find files that match a pattern, use glob():

from pathlib import Path

for pdf in sorted(Path("Downloads").glob("*.pdf")):
    print(pdf.name)
invoice-march.pdf
report final (2).pdf

glob("*.pdf") searches one folder; rglob("*.pdf") also searches every subfolder.

Task 1: Organize a Folder by File Type

This script sorts files into subfolders by extension. It runs as a dry run unless you say otherwise:

from pathlib import Path
import shutil

FOLDERS = {
    "Documents": {".pdf", ".docx", ".txt"},
    "Spreadsheets": {".xlsx", ".csv"},
    "Images": {".jpg", ".jpeg", ".png", ".gif"},
    "Installers": {".exe", ".msi", ".dmg"},
}

def organize(folder, dry_run=True):
    folder = Path(folder)
    for path in sorted(folder.iterdir()):
        if not path.is_file():
            continue
        for target, extensions in FOLDERS.items():
            if path.suffix.lower() in extensions:
                destination = folder / target / path.name
                print(f"{'Would move' if dry_run else 'Moving'} {path.name} -> {target}/")
                if not dry_run:
                    destination.parent.mkdir(exist_ok=True)
                    shutil.move(path, destination)
                break

organize("Downloads")
Would move budget.xlsx -> Spreadsheets/
Would move data.csv -> Spreadsheets/
Would move invoice-march.pdf -> Documents/
Would move logo.png -> Images/
Would move notes.txt -> Documents/
Would move report final (2).pdf -> Documents/
Would move setup.exe -> Installers/
Would move team photo.JPG -> Images/

The dry run shows exactly what would happen. When it looks right, run it for real with organize("Downloads", dry_run=False), and the folder ends up like this:

Documents/ ['invoice-march.pdf', 'notes.txt', 'report final (2).pdf']
Images/ ['logo.png', 'team photo.JPG']
Installers/ ['setup.exe']
Spreadsheets/ ['budget.xlsx', 'data.csv']

A few details make the script safe and reusable:

  • path.suffix.lower() treats .JPG and .jpg the same.
  • mkdir(exist_ok=True) creates each subfolder only if it doesn’t exist yet.
  • shutil.move() moves the file; nothing is deleted.
  • The FOLDERS dictionary is the only thing to change to add types, like .mp4 for videos.

Task 2: Rename Files in Bulk

File names with spaces, capital letters, and parentheses cause trouble in links, scripts, and some systems. This script cleans them up in every subfolder:

from pathlib import Path
import re

def clean_name(name):
    """'report final (2).pdf' -> 'report-final-2.pdf'"""
    stem, dot, ext = name.rpartition(".")
    stem = re.sub(r"[^a-z0-9]+", "-", stem.lower()).strip("-")
    return f"{stem}.{ext.lower()}"

for path in sorted(Path("Downloads").rglob("*")):
    if path.is_file():
        new_name = clean_name(path.name)
        if new_name != path.name:
            print(f"{path.name!r} -> {new_name!r}")
            path.rename(path.with_name(new_name))
'report final (2).pdf' -> 'report-final-2.pdf'
'team photo.JPG' -> 'team-photo.jpg'

The regular expression [^a-z0-9]+ matches any run of characters that aren’t lowercase letters or digits, and replaces each run with a single dash. The same pattern can add a date prefix, number scanned pages, or replace a client’s old name in every file.

Task 3: Archive Old Files

Find files that haven’t been changed in 30 days and move them to an archive folder:

from datetime import datetime, timedelta
from pathlib import Path
import shutil

cutoff = datetime.now() - timedelta(days=30)
archive = Path("Downloads/Archive")
archive.mkdir(exist_ok=True)

for path in sorted(Path("Downloads").rglob("*")):
    if path.is_file() and archive not in path.parents:
        modified = datetime.fromtimestamp(path.stat().st_mtime)
        if modified < cutoff:
            print(f"Archiving {path.name} (last changed {modified:%Y-%m-%d})")
            shutil.move(path, archive / path.name)
Archiving notes.txt (last changed 2026-10-16)
Archiving setup.exe (last changed 2026-10-16)

st_mtime is the time the file was last modified, as a timestamp; datetime.fromtimestamp() turns it into a date you can compare. The archive not in path.parents check skips files that are already in the archive. Change the move to path.unlink() only when you’re sure you want to delete for good.

Task 4: Make a Dated Zip Backup

shutil.make_archive() zips a whole folder in one line:

from datetime import date
from pathlib import Path
import shutil

backup_dir = Path("Backups")
backup_dir.mkdir(exist_ok=True)
archive = shutil.make_archive(
    str(backup_dir / f"documents-{date.today():%Y-%m-%d}"), "zip", root_dir="Downloads/Documents"
)
print("Created", Path(archive).name)
Created documents-2026-11-30.zip

Including the date in the name keeps one zip per day, so older backups aren’t overwritten. Copy the zips to another drive or cloud storage to follow the 3-2-1 rule.

Task 5: Combine CSV Reports

Three regions each send a CSV file with the same columns. Combine them into one file and total the sales:

import csv
from pathlib import Path

rows = []
for csv_file in sorted(Path("reports").glob("sales-*.csv")):
    with open(csv_file, newline="", encoding="utf-8") as f:
        rows.extend(csv.DictReader(f))

with open("all-sales.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=["date", "region", "amount"])
    writer.writeheader()
    writer.writerows(rows)

total = sum(int(row["amount"]) for row in rows)
print(f"Combined {len(rows)} rows into all-sales.csv, total ${total:,}")
Combined 5 rows into all-sales.csv, total $5,950

csv.DictReader reads each row as a dictionary keyed by the column names, and DictWriter writes them back out. For bigger or messier data, pandas does the same with pd.concat(), plus cleaning and analysis.

Keep a Log

A script that runs on a schedule has nobody watching it. Write what it does to a log file with the built-in logging module:

import logging

logging.basicConfig(
    filename="automation.log",
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(message)s",
)
logging.info("Organized 8 files")
logging.warning("Downloads folder is over 5 GB")
print(open("automation.log").read().count("\n"), "lines written to automation.log")
2 lines written to automation.log

Each line in automation.log gets a timestamp and a level (INFO, WARNING, ERROR), so you can check later what happened and when. Use logging.exception("...") inside an except block to record the full error.

Run Your Scripts on a Schedule

Once a script works, let the computer run it for you.

On macOS and Linux, use cron. Run crontab -e and add a line. This one runs the script every Monday at 8:00 a.m.:

0 8 * * 1 /home/maria/scripts/.venv/bin/python /home/maria/scripts/organize.py

The five fields are minute, hour, day of month, month, and day of week. Use full paths: cron doesn’t know your usual shell settings.

On Windows, use Task Scheduler. Create a task in the Task Scheduler app, or from a terminal:

schtasks /create /tn "Organize Downloads" /sc weekly /d MON /st 08:00 /tr "C:\Scripts\.venv\Scripts\python.exe C:\Scripts\organize.py"

In both cases, point to the Python inside your project’s virtual environment so the script gets the right packages, and check the log after the first scheduled run. For PowerShell-based automation on Windows, see PowerShell: A Beginner’s Guide for IT Administrators.

More Ideas to Automate

  • Reports: pull data from an API, build a CSV, and email it.
  • Monitoring: check disk space or whether a website is up, and log or alert on problems.
  • Spreadsheets: fill in or combine Excel files with openpyxl or pandas.
  • Images: resize or convert photos in bulk with Pillow.
  • Command-line tools: turn a script into a reusable tool with options, as shown in Build Command-Line Tools in Python With argparse.

Common Mistakes to Avoid

  • Running on real files first. Test on a copy, with a dry run.
  • Deleting instead of moving. Move files to an archive until you trust the script.
  • Overwriting files with the same name. Check destination.exists() before moving, and add a number or date if it does.
  • Relative paths in scheduled scripts. A scheduler may start in a different folder. Use full paths, or build them from Path(__file__).parent.
  • Silent failures. Log what the script does, and catch and log errors.

Frequently Asked Questions

Do I need to install anything?

No. pathlib, shutil, csv, datetime, and logging are all part of Python’s standard library. You only need Python itself.

pathlib or os.path?

Use pathlib for new code. It’s newer, more readable, and works with objects instead of strings. You’ll still see os.path in older tutorials, and both work.

Can Python automate clicking in other programs?

Yes, with libraries like PyAutoGUI, but it’s fragile: a moved window breaks it. When a program has an API, a command-line tool, or saves files you can read, automate those instead.

Conclusion

A few lines of Python can take over the small, repetitive jobs that fill your day: organizing folders, renaming files, archiving old documents, making backups, and combining reports. Use pathlib to find files, shutil to move and zip them, start every script with a dry run, log what it does, and let cron or Task Scheduler run it for you. Start with the one task you’re most tired of doing by hand.