Automated Python Backup Manager

1. Introduction

This project, originally developed in 2025, presents a practical example of how to implement an automated backup management system using Python. The focus is on time-based file manipulation and history preservation through structured logs.

2. Objectives

The main objective of this project is to develop an automation that allows evaluating the age of files, removing old backups (over 3 days old), copying recent files while preserving metadata, and generating audit logs.

3. Methodology and Code Analysis

The methodology is based on the exclusive use of native Python 3 libraries. Below are the architectural decisions and the main code snippets that make up the core of the system:

3.1 Safe Directory Manipulation

We used the pathlib library instead of the older os.path. It offers a much cleaner and more robust object-oriented interface for path manipulation, regardless of the operating system. The parents=True parameter ensures that the directory tree is created without throwing exceptions.

from pathlib import Path

SOURCE_DIR = Path.home() / "ambiente_de_teste_automacao" / "backupsFrom"
SOURCE_DIR.mkdir(parents=True, exist_ok=True)

3.2 Time-Based Retention Calculation

The combination of the datetime and timedelta classes allows us to dynamically calculate the cutoff point (threshold). Any file modified before this exact date will be marked for deletion.

from datetime import datetime, timedelta

DAYS_THRESHOLD = 3
time_threshold = datetime.now() - timedelta(days=DAYS_THRESHOLD)

3.3 Sorting Logic and Metadata Preservation

The logical core of the script. It compares the modification timestamp (st_mtime) against our time limit. For recent backups, we opted to use the shutil.copy2() function instead of simple copies, as it preserves the original file's metadata (such as the actual creation and modification dates of the backup).

import shutil

mod_time = datetime.fromtimestamp(file_path.stat().st_mtime)

if mod_time < time_threshold:
    file_path.unlink() # Remove the old file
else:
    # Copy the file preserving its metadata
    shutil.copy2(file_path, DEST_DIR)

4. Results and Execution

The developed system works as expected. Using an isolated script for environment preparation proved to be an excellent practice, allowing temporal deletion tests without the risk of actual data loss.

Demonstration of the test environment execution and backup routine.

5. Discussion

The project achieves its proposal of being a lightweight and functional automation tool. From a software architecture perspective, the separation of responsibilities (environment setup vs. business logic) ensures maintainability. For production server applications, the automation can be integrated with native scheduling tools (Cron/Task Scheduler).