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.
So for now, let’s just clean up this folder and delete it. And you can delete an empty folder using the
.rmdir() for remove directory method on a
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 now when I say
False, so this directory has been deleted. And using
.rmdir() only works if the director is empty. So if I tried to do that with, say, the
which contains three text files, then you’ll see that once I tried to call
.rmdir() on it, Python raises an
OSError and tells me the directory is not empty.
Okay, so using
.rmdir() like this doesn’t work. You’d have to first go and delete all of the files that are in there. So, of course you could write some code to do that.
You could say
for path in yearly_dir.iterdir(): and then you could say
path.unlink(), for example, if there are only files in there, right?
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.
02:43 You’ll first have to empty them.
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.
And you can only use
.rmdir() with empty folders. In the next lesson, you’ll learn to use
shutil, a different module in the standard library to delete non-empty directories.
Become a Member to join the conversation.