How to Clean Old Temp Files in Python

A Python script that scans a directory and deletes files older than a configurable age (default: one week), with safe error handling.

Easy Python 3.6+ Aug 9, 2026 Automation & scripting 13 views 0 copies

Python code

35 lines
Python 3.6+
import os
import time
from pathlib import Path

def clean_old_temp_files(directory=".", max_age_seconds=7 * 24 * 60 * 60):
    """
    Remove files in directory older than the specified age.
    
    Args:
        directory: Path to directory to clean
        max_age_seconds: Maximum age in seconds (default: 1 week)
    """
    cutoff_time = time.time() - max_age_seconds
    removed_count = 0
    skipped_count = 0

    for path in Path(directory).iterdir():
        if not path.is_file():
            continue
        try:
            file_age = path.stat().st_mtime
            if file_age < cutoff_time:
                path.unlink()
                removed_count += 1
                print(f"Removed: {path}")
            else:
                skipped_count += 1
        except (OSError, PermissionError) as e:
            print(f"Error processing {path}: {e}")

    print(f"Removed {removed_count} old files, skipped {skipped_count} recent files.")

if __name__ == "__main__":
    # Clean the current directory (or specify a temp directory)
    clean_old_temp_files("/tmp/test_temp")

Output

stdout
Removed: /tmp/test_temp/old_log_1.txt
Removed: /tmp/test_temp/old_backup.dat
Error processing /tmp/test_temp/locked_file.log: [Errno 13] Permission denied: '/tmp/test_temp/locked_file.log'
Removed 2 old files, skipped 1 recent files.

How it works

The script uses pathlib.Path.iterdir() to safely iterate over directory entries, skipping subdirectories with path.is_file(). File age is calculated using path.stat().st_mtime, which returns the last modification time in seconds since the epoch. The cutoff time is computed as time.time() - max_age_seconds, and files with mtime earlier than this threshold are deleted with path.unlink(). Each file is wrapped in a try/except block to handle permission errors and other OS-level issues gracefully, so one bad file doesn't crash the whole cleanup.

Common mistakes

  • Using `os.listdir()` and joining paths manually instead of `pathlib` which handles path edge cases automatically
  • Not catching `PermissionError` which will crash the script on locked or protected files
  • Deleting the directory itself by not checking `path.is_file()` first
  • Using `st_atime` (access time) instead of `st_mtime` (modification time) for age calculation

Variations

  1. Use `Path.rglob('*')` instead of `iterdir()` to clean files recursively in subdirectories, but add a safety check to avoid deleting the root
  2. Add a dry-run mode that prints files without unlinking, useful for testing before real cleanup

Real-world use cases

  • Scheduled cron jobs that clear out old download directories, cache folders, or log files on application servers.
  • CI/CD pipelines that purge stale build artifacts from workspace directories after a retention window.
  • Automated QA environments that cleanup temporary test data from shared folder mounts between test runs.

Sponsored

Run this sample

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

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.