Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Deleting a Non-Empty Folder

00:00 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.

00:20 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.

00:40 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.

00:56 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 "yearly".

01:13 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 shutil.

01:26 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.

01:56 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?

02:15 And I want to do this recursively, so I will use our .rglob().

02:21 And again, I will need to pass this to a list so that we can directly see the output.

02:32 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 shutil.rmtree().

02:48 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 shutil.

02:57 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.