Photo by freepik
Automating data backup from one folder to another is a useful task, especially to ensure data safety and recovery. Below is a Python script that automates this process using the shutil module, which provides functions to copy and move files. This script will copy all files from a source folder to a destination folder.
Steps:
- Specify Source and Destination Paths: Define where the data should be copied from and where it should go.
- Copy Files: Use the shutil module to copy all files and folders from the source directory to the destination directory.
- Handle Errors: Include error handling to manage any issues (like permission errors or missing folders).
Full Python Script:
import os
import shutil
from datetime import datetime
def backup_files(source_folder, destination_folder):
try:
# Check if source folder exists
if not os.path.exists(source_folder):
print(f"Source folder '{source_folder}' does not exist.")
return
# Create the destination folder if it doesn't exist
if not os.path.exists(destination_folder):
os.makedirs(destination_folder)
print(f"Created destination folder: {destination_folder}")
# Log the current time for versioning
current_time = datetime.now().strftime("%Y%m%d-%H%M%S")
backup_folder = os.path.join(destination_folder, f"backup_{current_time}")
os.makedirs(backup_folder)
# Copy files and directories
for item in os.listdir(source_folder):
source_path = os.path.join(source_folder, item)
dest_path = os.path.join(backup_folder, item)
if os.path.isdir(source_path):
shutil.copytree(source_path, dest_path) # Copy directories
print(f"Directory '{item}' copied successfully.")
else:
shutil.copy2(source_path, dest_path) # Copy files
print(f"File '{item}' copied successfully.")
print(f"Backup completed successfully to '{backup_folder}'")
except Exception as e:
print(f"Error occurred during backup: {e}")
# Paths to source and destination folders
source_folder = '/path/to/source/folder' # Replace with your source folder path
destination_folder = '/path/to/destination/folder' # Replace with your destination folder path
# Run the backupbackup_files(source_folder, destination_folder)
Explanation of the Script:
- os.path.exists(): This checks whether the source and destination directories exist. If the source directory doesn’t exist, the script will exit.
- os.makedirs(): This creates the destination folder and backup subfolder (if they don’t already exist).
- os.listdir(): This lists all the files and folders inside the source directory.
- shutil.copy2(): This copies individual files, preserving metadata (like timestamps).
- shutil.copytree(): This copies entire directories, including subdirectories and files.
- datetime.now().strftime(): This is used to create a timestamped folder inside the destination folder, ensuring each backup is unique.
- Error Handling: The try-except block captures and prints any errors that occur during the backup process.
How the Script Works:
- Backup Folders and Files: The script will recursively copy all files and folders from the source directory to a new, timestamped folder in the destination directory.
- Create Backup Folder: Every time the script runs, a new backup folder is created using the current timestamp (backup_YYYYMMDD-HHMMSS).
- Copy Directories and Files: If a directory is found, it is copied with all its contents using shutil.copytree(). If a file is found, it is copied with shutil.copy2().
Example Use Case:
If you have a folder with important project files located in C:/Users/YourName/Documents/ProjectFiles and you want to back them up to an external drive located at D:/Backup, you would modify the script as follows:
source_folder = ‘C:/Users/YourName/Documents/ProjectFiles’
destination_folder = ‘D:/Backup’
Read More about Technology “The Role of Cloud Computing in Driving Digital Transformation!”
Additional Features You Can Add:
- Scheduled Backups: Use a task scheduler like cron on Linux/macOS or Windows Task Scheduler to run this script automatically at specific times.
- Email Notifications: Send an email when the backup is complete or if an error occurs.
- Selective Backup: Modify the script to only backup files with certain extensions (e.g., .txt, .docx).
- Logging: Save a log file with details of the backup process (e.g., which files were copied, any errors).
Conclusion:
This Python script offers a simple yet effective way to automate backups from one folder to another. You can extend it further with features like compression (e.g., using the zipfile module) or more advanced error handling depending on your needs.
Leave a Reply