Maintenance

Site is under maintenance — quizzes are still available.

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

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.

Medium Python 3.9+ Jun 28, 2026 Automation & scripting 2 views 0 copies

Python code

50 lines
Python 3.9+
import 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

stdout
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

  1. Use `pathlib.Path.rglob()` for a more modern file traversal approach.
  2. 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

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 Automation & scripting

Related tutorials and quizzes for this topic.