Automatically Clean Temporary Files from Applications Using Python
A Python script that safely deletes temporary files from common application temp directories across Windows, Linux, and macOS, tracking cleaned count and disk space.
Python code
50 linesimport os
import shutil
import tempfile
import platform
def clean_application_temp_files():
"""Delete common temporary file locations safely."""
system = platform.system()
temp_dirs = []
if system == "Windows":
temp_dirs.extend([
os.path.join(os.getenv("LOCALAPPDATA"), "Temp"),
os.path.join(os.getenv("WINDIR"), "Temp"),
os.path.join(os.getenv("USERPROFILE"), "AppData", "Local", "Temp"),
])
elif system in ("Linux", "Darwin"): # Darwin = macOS
temp_dirs.extend([
tempfile.gettempdir(),
"/tmp",
os.path.expanduser("~/.cache"),
])
removed_count = 0
removed_bytes = 0
for temp_dir in temp_dirs:
if not os.path.isdir(temp_dir):
continue
for root, dirs, files in os.walk(temp_dir, topdown=False):
for name in files:
file_path = os.path.join(root, name)
try:
file_size = os.path.getsize(file_path)
os.remove(file_path)
removed_count += 1
removed_bytes += file_size
except (PermissionError, OSError):
pass
for name in dirs:
dir_path = os.path.join(root, name)
try:
shutil.rmtree(dir_path)
except (PermissionError, OSError):
pass
print(f"Cleaned {removed_count} files ({removed_bytes / 1024:.2f} KB).")
if __name__ == "__main__":
clean_application_temp_files()
Output
Cleaned 127 files (3456.78 KB).
How it works
The script detects the operating system with platform.system() and builds a list of common temporary file locations. It walks each directory bottom-up using os.walk() so that files are removed before their parent folders. Python's os.remove() and shutil.rmtree() handle individual files and directories, wrapped in try/except blocks to skip files locked by another process. The total count and size of removed files are printed for user feedback.
Common mistakes
- Not using `topdown=False` in `os.walk`, causing empty directory removal to fail.
- Forgetting to handle `PermissionError` on files in use by the operating system.
- Assuming all temp directories exist without checking with `os.path.isdir()`.
- Accidentally deleting important cache files by walking the wrong root path.
Variations
- Use `pathlib.Path.rglob()` for a more modern file traversal approach.
- Add a dry-run mode with `--dry-run` flag that lists files to delete without removing them.
Real-world use cases
- A system cleanup tool run weekly via cron or Task Scheduler to free up disk space.
- A pre-deployment step in CI pipelines that removes leftover temporary files before builds.
- A user-facing utility bundled in a desktop application to offer a one-click temp file cleanup.
Sponsored
More from Automation & scripting
- 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
- Automatically Log CPU, RAM, and Disk Usage Every Minute in Python easy
- Batch Rename Hundreds of Files in Python easy
- Benchmark File Read and Write Speed in Python medium
Keep learning
Related tutorials and quizzes for this topic.