Deleting an Empty Folder
In this lesson, you will learn how you can delete an empty folder using the
pathlib module. Now, if you remember, your folder structure currently looks like this, and you have an empty folder in here. Maybe you wanted to make some weekly plans, but you didn’t yet.
Here in IDLE, again, I need to first define the path to the directory I want to delete, so I’m going to say
weekly_dir is inside of the
notes_dir, inside of the
"plans" subdirectory, and then again in a subdirectory that’s called
That’s the right path to
weekly_dir. Let’s just double check that it’s—is directory. Okay, we found the correct path to the
weekly directory, and this directory is empty, which allows me to do
weekly_dir.rmdir(), remove directory. And after I call this, the directory is gone.
So this would delete all the files, and then afterwards you could again call
yearly_dir.rmdir(), and then it would delete the empty directory. However, this doesn’t work if there’s any subfolders in there, etc.
So I’m not going to do this now. Instead, in the next lesson, I will show you how you can delete non-empty directories using a different module of the standard library because using
pathlib, you can’t delete non-empty directories directly.
So to recap, in order to delete an empty folder, you can use the
.rmdir() method. This just works by defining the path to the director you want to delete, and then calling the
.rmdir() method on it. It doesn’t return anything, but it deletes the directory.
Become a Member to join the conversation.