Deleting a Non-Empty Folder
So, in the previous lesson, you managed to delete an empty folder using
pathlib.Path.rmdir(), but you also saw that it only works with empty folders. In this lesson, you’ll learn how you can delete a non-empty folder. And as a heads-up, this does not work with the
pathlib module, so you will have to use a different module.
Let’s take a look at the file structure. So for me, having this
yearly/ plans here is still a little bit too taunting, like who knows what I’m going to do in 3033, right? So for now, I’d just prefer to delete this whole folder and get rid of
yearly/, including all of the files that are in there.
And I can do this by using the built-in
shutil module and then a function that’s in this module called
rmtree(). This function allows you to delete a folder, including all of its contents.
So that’s exactly what we need here. I want to get rid of all of the files inside of
yearly/. So first I need to again define the path to
yearly/, and that’s inside of the
notes_dir / "plans" / and then
Can we double-check
.exists()? Okay, so we got the right path. The
yearly_dir exists. And now I need the different module. I need to import
So I’m going to say
import shutil, and then I will call
shutil.rmtree() and pass it the path. In this case, it’s going to be
yearly_dir, which, if you remember, contains three files. Now if I execute this, I don’t get any output returned, but if I now check again whether the
yearly_dir exists, you’ll see that it’s gone, and with it all the files.
Let’s confirm that there’s no more files with any year
33 in there anymore. So we’ll
.glob() throughout the whole
notes_dir and pass it the pattern anything ending with
33 and then anything afterwards, why not?
And I want to do this recursively, so I will use our
02:21 And again, I will need to pass this to a list so that we can directly see the output.
And as you can see, it’s empty. So all of these files that were nested inside of the
yearly/ directory got deleted when I deleted the directory using
So if you need to delete a non-empty folder, you can’t do that with
pathlib, but you can do it with a different built-in module called
And in order to do it, you need to import
shutil and then pass to
rmtree() the path to the folder that you want to delete. And this is how you can delete a non-empty folder using Python.
Become a Member to join the conversation.