Automate Your Backups With Python: Never Lose a File Again


Here is the uncomfortable truth behind most data-loss horror stories: the victim knew they should back up. They just never got around to it. Backups are also the single best defense against ransomware — an attacker can encrypt your files, but they cannot encrypt a backup they cannot reach.

So let us remove the “getting around to it” part. Today we build a Python backup script: it copies your important folders, stamps each backup with the date, compresses it, and deletes old backups automatically.

The Code

import os
import shutil
import datetime
SOURCE_DIRS = [
    os.path.expanduser("~/Documents"),
    os.path.expanduser("~/Pictures"),
]
BACKUP_ROOT = os.path.expanduser("~/Backups")
KEEP_LAST = 7
def make_backup():
    stamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M")
    dest = os.path.join(BACKUP_ROOT, f"backup_{stamp}")
    os.makedirs(dest, exist_ok=True)
    for src in SOURCE_DIRS:
        if not os.path.exists(src):
            print(f"Skipping missing folder: {src}")
            continue
        name = os.path.basename(src.rstrip("/"))
        shutil.copytree(src, os.path.join(dest, name))
        print(f"Backed up {src}")
    archive = shutil.make_archive(dest, "zip", dest)
    shutil.rmtree(dest)
    print(f"Archive created: {archive}")
    return archive
def cleanup_old():
    zips = sorted(f for f in os.listdir(BACKUP_ROOT) if f.endswith(".zip"))
    while len(zips) > KEEP_LAST:
        old = zips.pop(0)
        os.remove(os.path.join(BACKUP_ROOT, old))
        print(f"Deleted old backup: {old}")
if __name__ == "__main__":
    make_backup()
    cleanup_old()
    print("Done.")

How It Works

  • Copy: shutil.copytree duplicates each source folder into a timestamped backup directory.
  • Compress: shutil.make_archive zips it into a single file — easier to move, store and verify.
  • Rotate: the cleanup step keeps only your 7 most recent backups, so your disk never fills up silently.
  • Skip safely: missing folders print a warning instead of crashing the whole run.

Make It Automatic

A backup script you run manually is barely better than no backup. Schedule it:

crontab -e
0 2 * * * /usr/bin/python3 ~/backup.py >> ~/backup.log 2>&1

Now it runs while you sleep, and backup.log tells you if anything went wrong.

The 3-2-1 Rule

Professionals follow 3-2-1: 3 copies of your data, on 2 different media, with 1 offsite. Our script gives you copy two. For copy three, sync the backup folder to an external drive or cloud storage — and keep at least one backup disconnected from your computer. Ransomware encrypts every drive it can reach, including the always-plugged-in USB drive.

Test Your Backups

A backup you have never restored is a hope, not a backup. Once a month, unzip one archive and open a few files. If they open, your system works. If they do not, you found out on a calm Tuesday instead of during a crisis.

Level Up

  • Add email or messaging alerts when a backup fails.
  • Encrypt archives with a passphrase before uploading them anywhere.
  • Use rsync instead of full copies once your data grows large — it only copies what changed.

Backups are boring. Data loss is not. Automate the boring part today, and future-you will be grateful.

Comments

Popular Posts