AW Dev Rethought

Code is read far more often than it is written - Guido van Rossum

🧩 Python Automation Recipes – 🗂️ Folder Backup Automation


Description:

📌 Introduction

Backing up important folders manually is easy to forget and hard to keep consistent.

This automation recipe shows how to zip an entire folder and store it as a timestamped backup using Python.

It’s ideal for backing up:

  • project directories
  • documents
  • configuration folders
  • daily work snapshots

All without any external libraries.


🔎 Explanation

  • The script uses shutil.make_archive() to create a ZIP file.
  • A timestamp is appended to the backup name so each run creates a unique archive.
  • You define:
    • the folder to back up
    • the destination backup directory
  • The result is a clean, versioned backup you can run manually or schedule later.

This is one of the most common real-world automations developers rely on.


✅ Key Takeaways

  • 🗂️ Automate folder backups in seconds.
  • ⏱️ Timestamped archives prevent overwrites.
  • 📦 Uses only Python’s standard library — no dependencies.

Code Snippet:

import shutil
from pathlib import Path
from datetime import datetime

# --- Step 1: Configure paths ---

# Folder you want to back up
SOURCE_FOLDER = Path("/Users/abhijith/Documents/my_project")  # 🔁 change this

# Where backups should be stored
BACKUP_FOLDER = Path("/Users/abhijith/Documents/backups")     # 🔁 change this

# Ensure backup directory exists
BACKUP_FOLDER.mkdir(parents=True, exist_ok=True)

# --- Step 2: Generate timestamp ---
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")

# Backup file name (without extension)
backup_name = f"{SOURCE_FOLDER.name}_backup_{timestamp}"

# Full output path (without .zip)
backup_path = BACKUP_FOLDER / backup_name

# --- Step 3: Create ZIP archive ---
shutil.make_archive(
    base_name=str(backup_path),
    format="zip",
    root_dir=SOURCE_FOLDER
)

print(f"✅ Backup created successfully:")
print(f"📦 {backup_path}.zip")

Link copied!

Comments

Add Your Comment

Comment Added!