# Temporary File Cleaner

This utility cleans up temporary files from standard system locations to free up disk space. It iterates through the user's temporary directory and attempts to delete all files and folders within it.

**Modules Used:**
*   `os`: To get environment variables and handle paths.
*   [[programming/python/modules/shutil-module|shutil]]: To recursively delete directories.
*   [[programming/python/modules/pathlib-module|pathlib]]: For modern path manipulation.
*   [[programming/python/modules/argparse-module|argparse]]: To handle command-line arguments.

## The Code

Save this as `clean_temp.py`.

```python
import os
import shutil
import argparse
from pathlib import Path
import tempfile

def get_temp_dirs():
    """Returns a list of standard temporary directories for the current OS."""
    # Get the main user temp directory
    dirs = [tempfile.gettempdir()]
    
    # Add other common locations
    if os.name == 'nt': # Windows
        # Windows often uses multiple temp locations
        pass
    else: # Linux/macOS
        if os.path.exists('/var/tmp'):
            dirs.append('/var/tmp')
            
    return [Path(d) for d in dirs]

def clean_directory(directory, dry_run=False):
    if not directory.exists():
        print(f"Directory '{directory}' does not exist. Skipping.")
        return

    print(f"\nScanning '{directory}'...")
    
    deleted_files = 0
    deleted_folders = 0

    # Iterate over all items in the directory
    for item in directory.iterdir():
        try:
            if item.is_file() or item.is_symlink():
                if dry_run:
                    print(f"[DRY RUN] Would delete file: {item}")
                else:
                    item.unlink()
                    print(f"Deleted file: {item}")
                deleted_files += 1
            elif item.is_dir():
                if dry_run:
                    print(f"[DRY RUN] Would delete folder: {item}")
                else:
                    shutil.rmtree(item)
                    print(f"Deleted folder: {item}")
                deleted_folders += 1
        except PermissionError:
            print(f"Permission denied: Could not delete {item}")
        except Exception as e:
            print(f"Error deleting {item}: {e}")

    print(f"Cleanup summary for '{directory}':")
    print(f"  - Deleted {deleted_files} files.")
    print(f"  - Deleted {deleted_folders} folders.")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Temporary File Cleaner")
    parser.add_argument("--dry-run", action="store_true", help="Show what would be deleted without actually deleting")
    
    args = parser.parse_args()

    temp_dirs = get_temp_dirs()
    for d in temp_dirs:
        clean_directory(d, args.dry_run)
```

## Usage

```bash
# First, always run a dry run to see what will be deleted
python clean_temp.py --dry-run

# If you are happy with the dry run, execute the cleanup
# Note: You may need to run with Administrator/sudo privileges to delete all files
python clean_temp.py
```

[[programming/python/python]]