Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

How to Archive Old Files by Age in Python

Move files older than a specified number of days from a source directory to an archive directory using Python's pathlib and shutil modules.

Easy Python 3.9+ Jun 27, 2026 Files & data 1 views 0 copies

Python code

19 lines
Python 3.9+
import os
import shutil
import time
from pathlib import Path

def archive_old_files(source_dir: str, archive_dir: str, days_old: int) -> None:
    cutoff_time = time.time() - (days_old * 86400)  # 86400 seconds in a day
    archive_path = Path(archive_dir)
    archive_path.mkdir(parents=True, exist_ok=True)

    for item in Path(source_dir).iterdir():
        if item.is_file() and item.stat().st_mtime < cutoff_time:
            dest = archive_path / item.name
            shutil.move(str(item), str(dest))
            print(f"Archived: {item.name}")

if __name__ == "__main__":
    # Example usage: archive files older than 30 days
    archive_old_files("./source", "./archive", 30)

Output

stdout
Archived: old_report.pdf
Archived: backup_20230101.csv
Archived: temp_data.log

How it works

This script calculates a cutoff timestamp by subtracting days_old * 86400 seconds from the current time. Each file's last modification time (st_mtime) is compared to this cutoff. Path.mkdir(parents=True, exist_ok=True) ensures the archive directory exists. shutil.move transfers the file, and a confirmation message is printed for each archived file.

Common mistakes

  • Using `st_ctime` (creation time) instead of `st_mtime` (modification time) for age-based logic.
  • Forgetting to handle files without read permissions by catching `PermissionError`.
  • Not handling the case where a file with the same name already exists in the archive directory.
  • Using integer division instead of floating point for days_old calculation, losing precision.

Variations

  1. Use `os.scandir()` with a for loop for better performance on large directories.
  2. Add optional `recursive=True` parameter to archive files from subdirectories using `Path.glob('**/*')`.

Real-world use cases

  • Automated cleanup of log files in a web server's logging directory that are older than 90 days.
  • Archiving completed project directories from a shared team drive to cold storage after 365 days.
  • Housekeeping temporary files in a data pipeline's working directory that are older than 7 days.

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.