The user wants a Python script to automate backups with version control.
"Version control" in the context of backups usually means keeping multiple snapshots of the data over time (e.g., daily backups), not necessarily using Git (though Git is a possibility, it's often bad for large binary backups).
I should clarify or choose the most practical approach. A common approach for "versioned backups" is keeping a timestamped copy or using hard links (rsync-style) to save space.
However, since the prompt asks for a "Python script", I should build something self-contained if possible, or use standard libraries.
Approach 1: Simple copy with timestamps.
- Copy source to destination + timestamp folder.
- Pros: Easy to understand.
- Cons: Wastes space if files haven't changed.
Approach 2: Git.
- Initialize a repo in the backup folder. Add/Commit.
- Pros: True version control.
- Cons: Terrible for large files, binary files, or full system backups. Repo gets huge and slow.
Approach 3: Incremental/Hard-link based (like rsync).
- Python's
shutil and os modules can do this, but it's complex to implement hard-link logic manually in pure Python.
- Actually, it's easier to wrap
rsync if on Linux/Mac, but the user might be on Windows.
Approach 4: Zip files with timestamps.
- Compress source into a .zip named with the date.
- Pros: Portable, clean.
- Cons: Slow for large backups, compression overhead.
Decision: I will provide a robust script that uses Approach 4 (Zip files) as the default because it's the most cross-platform and easy to run without external dependencies (like rsync or git installed).
However, I will also mention that for "professional" version control of code, Git is better, and for "system" backups, rsync is better.
Let's refine the requirements for the script:
- Configuration: Source directory, Destination directory.
- Versioning: Create a zip file named
backup_YYYY-MM-DD_HH-MM-SS.zip.
- Rotation (Cleanup): Keep only the last N backups to save space.
- Logging: Print what's happening.
Let's create a class-based structure for cleanliness.
Drafting the Code:
- Imports:
os, shutil, datetime, time, sys, argparse (for command line args).
- Function
create_backup(src, dst):
- Check if src exists.
- Create dst if not exists.
- Generate timestamp.
- Zip the source.
- Print success.
- Function
rotate_backups(dst, keep_count):
- List files in dst.
- Sort by modification time.
- Delete oldest if count > keep_count.
Refining the "Version Control" aspect:
If the user literally meant "backup code using Git", I should provide a snippet for that too, just in case. But "automate backups" usually implies documents, photos, or mixed data.
Let's stick to the Timestamped Zip approach as the primary solution because it's universally applicable. I will add comments explaining how to schedule it (cron/Task Scheduler).
Structure of the response:
- Introduction: Explain the approach (Timestamped Archives).
- The Python Script:
- Configuration section.
- Backup logic (zipping).
- Rotation logic (cleaning old files).
- Main execution block.
- How to use it: Instructions on setup and automation (Cron/Task Scheduler).
- Alternative (Git): Briefly mention if they strictly meant code versioning.
Script details:
- Use
shutil.make_archive for zipping. It's easy.
- Use
argparse so the user can run python backup.py /path/to/source /path/to/dest --keep 5.
- Add error handling (try/except).
Self-Correction during drafting:
shutil.make_archive creates a zip, but the path handling can be tricky (absolute vs relative paths inside the zip).
To make the zip clean (no full absolute paths like C:/Users/...), I need to handle the directory context.
Actually, shutil.make_archive(base_name, 'zip', root_dir, base_dir) handles this.
root_dir: The directory to change to before archiving.
base_dir: The directory relative to root_dir to archive.
So if I want to backup /home/user/data, I should set root_dir='/home/user' and base_dir='data'. Or just root_dir=src and base_dir='.'.
Let's keep it simple: shutil.make_archive(backup_name, 'zip', source_dir). This usually puts the contents of source_dir at the root of the zip, or the folder itself depending on implementation. Let's test mentally:
shutil.make_archive("output", "zip", "my_folder") -> creates output.zip containing the contents of my_folder. This is usually what people want.
Let's write the code.
import os
import shutil
import datetime
import argparse
from distutils.dir_util import copy_tree # maybe not needed if using zip
Wait, distutils is deprecated in newer Python. Stick to shutil.
Cleanup Logic:
- Get list of files in dest.
- Filter for backup files (extension check).
- Sort by creation/mod time.
- Slice off the tail (the ones to keep) and delete the rest.
Enhancement: Exclude certain file types? Maybe too complex for a basic script. Keep it simple.
Final Plan:
- Script Name:
auto_backup.py
- Arguments:
source, destination, --retain (number of backups to keep).
- Logic:
- Verify paths.
- Create zip.
- Rotate old zips.
- Log output.
Let's produce the response.
Here is a complete, robust Python script to automate backups with version control.
This script uses a Timestamping Strategy. It compresses your source folder into a .zip file named with the current date and time (e.g., backup_2023-10-27_14-30-00.zip). It also includes a Retention Policy feature to automatically delete old backups so your drive doesn't fill up.
The Python Script (auto_backup.py)
Save the following code into a file named auto_backup.py.
import os
import shutil
import argparse
import sys
from datetime import datetime
def create_backup(source, destination, retain_count):
"""
Creates a zipped backup of the source directory in the destination directory.
Manages retention by deleting old backups.
"""
# 1. Validate Paths
if not os.path.exists(source):
print(f"Error: Source directory '{source}' does not exist.")
return
if not os.path.exists(destination):
print(f"Creating destination directory: {destination}")
os.makedirs(destination)
# 2. Generate Filename with Timestamp
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
source_folder_name = os.path.basename(os.path.normpath(source))
zip_filename = f"{source_folder_name}_backup_{timestamp}"
# full path for shutil.make_archive expects the filename WITHOUT .zip extension
zip_path = os.path.join(destination, zip_filename)
print(f"Starting backup of '{source}'...")
try:
# 3. Create the Zip Archive
# make_archive(base_name, format, root_dir)
shutil.make_archive(zip_path, 'zip', source)
print(f"Success: Backup created at '{zip_path}.zip'")
except Exception as e:
print(f"Error during backup: {e}")
return
# 4. Retention Policy (Cleanup old backups)
if retain_count > 0:
cleanup_old_backups(destination, source_folder_name, retain_count)
def cleanup_old_backups(destination, folder_name, keep_count):
"""
Finds backups matching the pattern and deletes the oldest ones,
keeping only 'keep_count'.
"""
print(f"Applying retention policy (keeping last {keep_count})...")
# List all files in destination
files = os.listdir(destination)
# Filter files that look like our backups for this specific folder
# Pattern: folder_name_backup_TIMESTAMP.zip
prefix = f"{folder_name}_backup_"
backups = [f for f in files if f.startswith(prefix) and f.endswith('.zip')]
# Sort by name (since timestamp is in name, alphabetical = chronological)
backups.sort()
# Determine how many to delete
files_to_delete = len(backups) - keep_count
if files_to_delete > 0:
print(f"Found {len(backups)} backups. Deleting {files_to_delete} old backup(s)...")
# Delete the oldest files (the first ones in the sorted list)
for i in range(files_to_delete):
file_to_remove = os.path.join(destination, backups[i])
try:
os.remove(file_to_remove)
print(f"Deleted old backup: {backups[i]}")
except OSError as e:
print(f"Error deleting {backups[i]}: {e}")
def main():
parser = argparse.ArgumentParser(description="Python Versioned Backup Script")
parser.add_argument("source", help="Path to the folder you want to back up")
parser.add_argument("destination", help="Path to the folder where backups will be stored")
parser.add_argument("--retain", type=int, default=0,
help="Number of recent backups to keep. Older ones will be deleted. (Default: 0 = keep all)")
args = parser.parse_args()
create_backup(args.source, args.destination, args.retain)
if __name__ == "__main__":
main()
How to use it
You run this script from your command line (Terminal or Command Prompt).
1. Basic Usage
To back up a folder named MyProject to a folder named Backups:
python auto_backup.py "C:/Users/Name/Documents/MyProject" "C:/Users/Name/Backups"
Result: Creates MyProject_backup_2023-10-27_10-00-00.zip inside Backups.
2. With Version Control (Retention)
To keep only the last 5 backups and automatically delete older ones to save space:
python auto_backup.py "C:/Users/Name/Documents/MyProject" "C:/Users/Name/Backups" --retain 5
How to Automate it (Run automatically)
You don't want to type this command manually every day. Here is how to schedule it.
On Windows (Task Scheduler)
- Open Task Scheduler.
- Click Create Basic Task.
- Name it "Python Backup" and select Daily.
- Action: Start a program.
- Program/script: Path to your python.exe (e.g.,
C:\Python39\python.exe).
- Tip: Run
where python in cmd to find this path.
- Add arguments: The full command arguments.
Example:
C:\Scripts\auto_backup.py "C:\Source" "D:\Backups" --retain 5
- Start in: The folder where your script lives (e.g.,
C:\Scripts\).
On Linux / macOS (Cron)
- Open Terminal.
- Type
crontab -e.
- Add a line to run it every day at 2 AM:
0 2 * * * /usr/bin/python3 /home/user/scripts/auto_backup.py "/home/user/source" "/home/user/backups" --retain 7
How the "Version Control" works here
This script handles Backup Versioning, not Code Versioning (like Git).
- Snapshots: It takes a snapshot of your files at a specific moment.
- Non-Destructive: It never modifies the original files.
- Isolation: If your data gets corrupted on Monday, you can restore the zip from Sunday. Unlike syncing (Dropbox/OneDrive), a corrupted file won't overwrite the backup immediately.