Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to delete only empty folders in Python?
In this tutorial, we will learn how to delete only empty folders in Python. As you delete files or uninstall programs, empty folders might build up over time, but they can be challenging to locate and manually eliminate. Fortunately, Python offers a quick and effective way to delete empty directories automatically.
Approach
We can use the built-in os module to identify and delete empty folders using Python. Here's the basic workflow of how we can achieve this ?
Use
os.walk()to traverse the file system recursively, starting at a given root directory.For each directory encountered during the traversal, use
os.listdir()to get a list of files and subdirectories contained within the directory.If the list returned by
os.listdir()is empty, we can assume the directory is empty, and delete it usingos.rmdir().If the list is not empty, recursively continue the traversal on each subdirectory within the directory.
Creating the delete_empty_folders() Function
Let's create a delete_empty_folders() function using this approach ?
import os
def delete_empty_folders(root):
for dirpath, dirnames, filenames in os.walk(root, topdown=False):
for dirname in dirnames:
full_path = os.path.join(dirpath, dirname)
if not os.listdir(full_path):
print(f"Deleting empty directory: {full_path}")
os.rmdir(full_path)
How This Code Works
The
delete_empty_folders()function takes a single argumentroot, which specifies the starting directory for the traversal.os.walk()traverses the file system recursively, returning a tuple containing the directory path (dirpath), subdirectory names (dirnames), and filenames (filenames).We use
topdown=Falseto traverse directories in reverse order, deleting the deepest empty directories first.For each directory, we construct the full path using
os.path.join()and check if it's empty usingos.listdir().If the directory is empty, we delete it using
os.rmdir().
Example 1: Basic Empty Folder Deletion
Let's test our function with a simple directory structure ?
import os
def delete_empty_folders(root):
for dirpath, dirnames, filenames in os.walk(root, topdown=False):
for dirname in dirnames:
full_path = os.path.join(dirpath, dirname)
if not os.listdir(full_path):
print(f"Deleting empty directory: {full_path}")
os.rmdir(full_path)
# Create test folder structure
root = "test_folder"
os.makedirs(os.path.join(root, "empty_folder"), exist_ok=True)
os.makedirs(os.path.join(root, "nonempty_folder"), exist_ok=True)
with open(os.path.join(root, "nonempty_folder", "file.txt"), "w") as f:
f.write("This is a test file.")
# Delete empty folders
delete_empty_folders(root)
Deleting empty directory: test_folder/empty_folder
After running this code, only the nonempty_folder remains in the test_folder directory.
Example 2: Multiple Empty Folders
Let's test with multiple empty folders ?
import os
def delete_empty_folders(root):
for dirpath, dirnames, filenames in os.walk(root, topdown=False):
for dirname in dirnames:
full_path = os.path.join(dirpath, dirname)
if not os.listdir(full_path):
print(f"Deleting empty directory: {full_path}")
os.rmdir(full_path)
# Create test folder structure
root = "test_folder2"
os.makedirs(os.path.join(root, "empty_folder1"), exist_ok=True)
os.makedirs(os.path.join(root, "empty_folder2"), exist_ok=True)
os.makedirs(os.path.join(root, "nonempty_folder"), exist_ok=True)
with open(os.path.join(root, "nonempty_folder", "file1.txt"), "w") as f:
f.write("This is the 1st test file.")
with open(os.path.join(root, "nonempty_folder", "file2.txt"), "w") as f:
f.write("This is the 2nd test file.")
# Delete empty folders
delete_empty_folders(root)
Deleting empty directory: test_folder2/empty_folder1 Deleting empty directory: test_folder2/empty_folder2
Both empty_folder1 and empty_folder2 are deleted, leaving only the nonempty_folder.
Enhanced Version with Error Handling
For production use, consider adding error handling ?
import os
def delete_empty_folders_safe(root):
deleted_count = 0
for dirpath, dirnames, filenames in os.walk(root, topdown=False):
for dirname in dirnames:
full_path = os.path.join(dirpath, dirname)
try:
if not os.listdir(full_path):
os.rmdir(full_path)
print(f"Deleted: {full_path}")
deleted_count += 1
except OSError as e:
print(f"Error deleting {full_path}: {e}")
print(f"Total empty folders deleted: {deleted_count}")
Key Points
Use
topdown=Falseinos.walk()to delete nested empty directories firstos.listdir()returns an empty list for empty directoriesos.rmdir()only removes empty directoriesAlways test on a small directory structure before running on important folders
Consider adding error handling for production use
Conclusion
Python's os module provides an efficient way to identify and delete empty folders automatically. Use os.walk() with topdown=False to traverse directories bottom-up, ensuring nested empty folders are deleted properly.
