Automating File Backups
Backup strategy (simple and effective)
Section titled “Backup strategy (simple and effective)”- choose what to back up
- create timestamped archives
- store backups in a separate location
Zip a folder
Section titled “Zip a folder”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
Visualize it
Section titled “Visualize it”A backup script moves files from the source folder to a safe destination in a few clear steps.
flowchart LR
A["Scan source folder"] --> B["Select files to back up"]
B --> C["Compress into zip archive"]
C --> D["Copy to backup destination"]
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – List Files with os.listdir
Section titled “Exercise 1 – List Files with os.listdir”Exercise 2 – Join Paths with os.path.join
Section titled “Exercise 2 – Join Paths with os.path.join”Exercise 3 – Write and Read a File
Section titled “Exercise 3 – Write and Read a File”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading