Skip to main content

Command Palette

Search for a command to run...

How to Create a Folder Backup Script in Python

Updated
3 min read
How to Create a Folder Backup Script in Python

Introduction

Backing up folders is a simple but essential task. Whether you're saving project files, documents, or media folders, automating this process can save time and protect against accidental deletion, data corruption, or system failure.

In this guide, we'll walk through a Python script that:

  • Takes a folder path as input

  • Creates a timestamped backup copy of the folder

  • Saves it to a designated backup directory

You can also schedule this script to run regularly using a task scheduler.

Tools Required

You’ll only need standard Python libraries:

import os
import shutil
from datetime import datetime
  • os: For file and folder path handling

  • shutil: For copying the folder and its contents

  • datetime: For generating timestamps to version your backups

No extra installations required!

Step-by-Step Folder Backup Script

Step 1: Import Required Modules

import os
import shutil
from datetime import datetime

Explanation: These built-in modules will handle directory copying and timestamp creation.

Step 2: Define Source and Backup Folders

source_folder = r"C:\Users\YourName\Documents\ImportantFiles"  # Folder to back up
backup_root = r"C:\Users\YourName\Documents\Backups"           # Backup location

Explanation:

  • source_folder: The folder you want to back up.

  • backup_root: Where the backups will be stored.

Replace these paths with your actual directories.

Step 3: Generate Timestamp for Backup Folder

timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_folder_name = f"backup_{timestamp}"
backup_folder_path = os.path.join(backup_root, backup_folder_name)

Explanation:
This creates a unique folder name like backup_20250513_153022, ensuring that each backup is distinct and timestamped.

Step 4: Create the Backup

try:
    shutil.copytree(source_folder, backup_folder_path)
    print(f"Backup created successfully at: {backup_folder_path}")
except Exception as e:
    print("Backup failed:", e)

Explanation:

  • shutil.copytree() copies the entire folder and subfolders.

  • If the backup fails (e.g., path error, permission issue), it prints an error.

Full Script: Folder Backup Tool

import os
import shutil
from datetime import datetime

# === Step 1: Define your folders ===
source_folder = r"C:\Users\YourName\Documents\ImportantFiles"  # Folder to back up
backup_root = r"C:\Users\YourName\Documents\Backups"           # Where to store backups

# === Step 2: Create timestamped backup folder name ===
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_folder_name = f"backup_{timestamp}"
backup_folder_path = os.path.join(backup_root, backup_folder_name)

# === Step 3: Perform the backup ===
try:
    shutil.copytree(source_folder, backup_folder_path)
    print(f"✅ Backup successful!\nSaved to: {backup_folder_path}")
except Exception as e:
    print("❌ Backup failed:", e)

Optional Enhancements

1. Automate Daily Backups

Use Task Scheduler (Windows) or cron (Linux/macOS) to run this script on a schedule.

2. Auto-Cleanup Old Backups

Keep only the last 5 backups:

def cleanup_old_backups(folder, max_backups=5):
    backups = sorted([f for f in os.listdir(folder) if f.startswith('backup_')])
    while len(backups) > max_backups:
        old_backup = os.path.join(folder, backups.pop(0))
        shutil.rmtree(old_backup)
        print(f"Deleted old backup: {old_backup}")

3. Compress the Backup

Use shutil.make_archive() to zip the folder:

shutil.make_archive(backup_folder_path, 'zip', source_folder)

Why Use a Backup Script?

  • Version control for local folders

  • Backup before deploying code

  • Data loss prevention

  • Automate repeated backup tasks for peace of mind

Final Thoughts

With just a few lines of Python, you can automate and version your backups safely. This script is flexible enough to be customized with email notifications, file exclusions, or cloud uploads (to Google Drive or S3) in future versions.

Happy Scripting ! !

More from this blog

PyScript Academy

29 posts

PyScript Academy is a blog sharing practical Python scripts, tips, and mini projects—helping you learn Python by doing, one useful script at a time.