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.
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
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?
Become a Member to join the conversation.