The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Detect and delete empty folders

To detect and delete empty folders, here’s a Python script that recursively scans a directory and removes all empty folders:

python
import os def delete_empty_folders(directory): # Walk through the directory from bottom up for dirpath, dirnames, filenames in os.walk(directory, topdown=False): # Check if the folder is empty if not dirnames and not filenames: try: os.rmdir(dirpath) print(f"Deleted empty folder: {dirpath}") except OSError as e: print(f"Failed to delete {dirpath}: {e}") # Replace this path with the target directory target_directory = "/path/to/your/folder" delete_empty_folders(target_directory)

How It Works:

  • Uses os.walk with topdown=False to ensure it processes subfolders before their parents.

  • Checks if both dirnames and filenames are empty, meaning the folder is empty.

  • Uses os.rmdir() to delete the folder.

Notes:

  • Only deletes truly empty folders (no files or subfolders inside).

  • Update target_directory to your actual path.

Let me know if you need a version with a GUI, a CLI interface, or to run on specific platforms like Windows only.

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About