# Find and Delete Empty Folders

This utility recursively scans a directory and deletes any subfolders that are empty. It's useful for cleaning up project directories or file systems after moving or deleting many files.

**Modules Used:**
*   `os`: To walk through directories and remove them.
*   [[programming/python/modules/argparse-module|argparse]]: To handle command-line arguments.

## The Code

Save this as `clean_empty.py`.

```python
import os
import argparse
import sys

def find_and_delete_empty(directory, dry_run=False):
    if not os.path.isdir(directory):
        print(f"Error: Directory '{directory}' not found.")
        return

    deleted_count = 0
    
    # We use topdown=False to process from the deepest directories up
    for root, dirs, files in os.walk(directory, topdown=False):
        # Check if the current directory is empty
        if not dirs and not files:
            try:
                if dry_run:
                    print(f"[DRY RUN] Would delete empty folder: {root}")
                else:
                    os.rmdir(root)
                    print(f"Deleted empty folder: {root}")
                deleted_count += 1
            except OSError as e:
                print(f"Error deleting {root}: {e}")

    if deleted_count == 0:
        print("No empty folders found.")
    else:
        print(f"\nCleanup complete. Deleted {deleted_count} empty folders.")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Find and Delete Empty Folders")
    parser.add_argument("directory", help="The root directory to scan")
    parser.add_argument("--dry-run", action="store_true", help="Show what would be deleted without actually deleting")
    
    args = parser.parse_args()
    
    find_and_delete_empty(args.directory, args.dry_run)
```

## Usage

```bash
# First, always run a dry run to see what will be deleted
python clean_empty.py ./my_project --dry-run

# If you are happy with the dry run, execute the deletion
python clean_empty.py ./my_project
```

**How it works:**
The script uses `os.walk(directory, topdown=False)`. The `topdown=False` argument is crucial because it makes the function traverse the directory tree from the bottom up. This ensures that a folder containing an empty subfolder is not considered empty until after its empty subfolder has been deleted.

[[programming/python/python]]