Skip to content

Automating File Backups

  • choose what to back up
  • create timestamped archives
  • store backups in a separate location
backup_zip.py
from __future__ import annotations
 
from datetime import datetime
from pathlib import Path
import shutil
 
 
def backup_folder(folder: Path, out_dir: Path) -> Path:
    folder = folder.resolve()
    out_dir.mkdir(parents=True, exist_ok=True)
 
    stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    archive_base = out_dir / f"{folder.name}_{stamp}"
 
    # creates archive_base.zip
    archive_path = shutil.make_archive(str(archive_base), "zip", root_dir=str(folder))
    return Path(archive_path)
 
 
p = backup_folder(Path("./demo"), Path("./backups"))
print("created", p)
  • keep multiple backups
  • test restore occasionally
  • don’t back up into the same folder you’re archiving

A backup script moves files from the source folder to a safe destination in a few clear steps.

diagram File backup flow mermaid
How a backup script moves files from source to destination

Exercise 2 – Join Paths with os.path.join

Section titled “Exercise 2 – Join Paths with os.path.join”

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading