🐍 Python 3.10+

Clean Up The Windows Internet cache (INetCache) (Python)

Reports the size of the Windows Internet cache (INetCache) and optionally clears it out. Dry-run by default.

By WindowsScripting.com · 1.3 KB
cleanup_browser_cache.py
#!/usr/bin/env python3
"""
cleanup_browser_cache.py

Cleans up the Windows Internet cache (INetCache). Dry-run by default; pass --apply to actually delete.

Usage:
    python cleanup_browser_cache.py
    python cleanup_browser_cache.py --apply
"""

import argparse
import os
import shutil
from pathlib import Path


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--apply", action="store_true", help="Actually delete (default: dry run)")
    args = parser.parse_args()

    target = Path(os.path.expandvars(r'%LOCALAPPDATA%\Microsoft\Windows\INetCache'))
    if not target.exists():
        print(f"{target} does not exist on this machine.")
        return

    entries = list(target.iterdir())
    total_bytes = sum(f.stat().st_size for f in target.rglob("*") if f.is_file())
    print(f"{target}: {len(entries)} item(s), {total_bytes / 1024 / 1024:.2f} MB")

    if not args.apply:
        print("Run again with --apply to actually delete these items.")
        return

    for entry in entries:
        try:
            if entry.is_dir():
                shutil.rmtree(entry, ignore_errors=True)
            else:
                entry.unlink(missing_ok=True)
        except OSError:
            pass
    print("Cleanup complete.")


if __name__ == "__main__":
    main()