Python Automatic Backup Script for Specified Directories
This tutorial demonstrates how to create a Python script that automatically backs up a chosen source folder to a target location every minute, using shutil and os modules to copy files into timestamped directories for reliable data protection.
In this tutorial we introduce a Python project that automatically backs up a specified source directory to a target location, ensuring important data is protected.
First we define the source and target directories and import the required modules (shutil, os, datetime).
import shutil
import os
import datetime
# source directory
source_dir = "C:/Users/Administrator/Desktop/backup/source"
# target directory
target_dir = "C:/Users/Administrator/Desktop/backup/target"Next we create a backup function that generates a timestamped backup folder in the target directory and copies all files from the source using shutil.copy.
def backup_files():
"""Copy all files from source to a new backup directory"""
backup_dir_name = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
backup_dir = os.path.join(target_dir, backup_dir_name)
os.makedirs(backup_dir)
for file_name in os.listdir(source_dir):
source_file = os.path.join(source_dir, file_name)
target_file = os.path.join(backup_dir, file_name)
shutil.copy(source_file, target_file)Finally we add a main loop that runs the backup function every minute.
if __name__ == '__main__':
while True:
backup_files()
time.sleep(60)Running the script creates a new timestamped backup folder each minute, providing continuous protection of the data, and can be extended with libraries such as paramiko or pysftp for cross‑platform automated backups.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.