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. Now, we'll be discussing how to delete empty folders in Python.

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 −

  • We can use os.walk() to traverse the file system recursively, starting at a given root directory.

  • For each directory encountered during the traversal, we can 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 we can delete it using os.rmdir().

  • If the list is not empty, we can recursively call the same function on each subdirectory within the directory, continuing the traversal.

Now let’s create a delete_empty_folders() function using this. The syntax is given below −

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): 
            os.rmdir(full_path)

Let's Break Down how this Code Works

  • The delete_empty_folders() function takes a single argument root, which specifies the starting directory for the traversal. We use os.walk() to traverse the file system recursively, starting at the root.

  • For each directory encountered during the traversal, os.walk() returns a tuple containing the path to the directory (dirpath), a list of the names of subdirectories within the directory (dirnames), and a list of the names of files within the directory (filenames).

  • We traverse the dirnames list in reverse order (using topdown=False) so that we delete the deepest empty directories first. For each directory in dirnames, we construct the full path to the directory using os.path.join().

  • If the directory is empty (i.e., if os.listdir(full_path) returns an empty list), we print a message indicating that we're deleting the directory. Then we use os.rmdir() to delete the directory.

And that's it! With this code, we can identify and delete empty directories starting from a given root directory.

Example

Before we run our delete_empty_folders() function on our entire file system, let's test it out on a smaller subset of directories to make sure it's working correctly.

Here's an example directory structure we can use for testing −

test_folder/
   empty_folder/
   nonempty_folder/
      file.txt

We can create this directory structure using the following Python code and then call the delete_empty_folders() function on the test_folder directory −

import os

# Create test folder structure
root = "test_folder"
os.makedirs(os.path.join(root, "empty_folder"))
os.makedirs(os.path.join(root, "nonempty_folder"))
with open(os.path.join(root, "nonempty_folder", "file.txt"), "w") as f: f.write("This is a test file.")
delete_empty_folders(root)

Output

Deleting empty directory: test_folder\empty_folder

If we check the test_folder directory again, we should see that the empty_folder has been deleted, leaving us with the only nonempty_folder in the test_folder directory.

Example

Now let’s take a quick look at another case. Here’s an example directory structure we can use for the testing −

test_folder/
   nonempty_folder/
      file1.txt
		file2.txt
	empty_folder1/
	empty_folder2/

We can create this directory structure using the following Python code and then call the delete_empty_folders() function on the test_folder directory −

import os

# Create test folder structure
root = "test_folder"
os.makedirs(os.path.join(root, "empty_folder1"))
os.makedirs(os.path.join(root, "empty_folder2"))
os.makedirs(os.path.join(root, "nonempty_folder"))
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(root)

Output

Deleting empty directory: test_folder\empty_folder1
Deleting empty directory: test_folder\empty_folder2

If we check the test_folder directory again, we should see that both empty_folder1 and empty_folder2 have been deleted, leaving us only nonempty_folder in the test_folder directory.

Conclusion

In this tutorial, we've learned how to use Python to identify and delete empty folders on our file system. With the code and techniques we've covered in this tutorial, we now have a powerful tool for managing our file system and keeping it organized. Whether we're cleaning up after a large data analysis project or simply trying to keep our computer running smoothly, the ability to identify and delete empty folders using Python can save us time and make our lives easier.

Updated on: 12-May-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements