Deleting an Empty Folder
00:00
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.
00:14
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 Path
object.
00:28
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 "weekly"
.
00:49
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.
01:12
So now when I say weekly_dir.exists()
,
01:18
I get 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 yearly
directory,
01:39
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.
01:54
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.
02:03
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?
02:17
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.
02:29
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.
02:48
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.
03:04
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.