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.
Python code
35 linesimport 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
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
- Use `Path.rglob('*')` instead of `iterdir()` to clean files recursively in subdirectories, but add a safety check to avoid deleting the root
- 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
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.