Deleting a Directory
Okay, last exercise. Let’s look at that one. Delete the `my_folder/` directory. So the last task is to get rid of all the hard work that you just did and put your home folder back into its original state, which means we want to delete
my_folder/ and anything that’s inside of
pathlib doesn’t actually allow you to do this.
One way to delete
my_folder/ would be to go over all the files that are inside the
my_folder/ directory or its subdirectory,
images/, and first delete the files and then remove the empty folders.
Okay, I’m going to import
shutil. Then I want to use the
.rmtree() method. That stands for remove tree. But before I do this, like I said, I want to be careful, so let’s double check that
my_folder/ is actually what I expected it to be.
Okay, looks good.
file2.txt—you know these are empty—some
.DS_Store file that macOS creates, and an an
images/ folder. Now, okay, so what’s inside of that
images/ folder? Did I, did I maybe like accidentally move a really important image in there? Just to make sure, I want to also list everything that’s in there.
And then again, I’m passing the results, the object that gets generated from
.rglob(), to the
list() function so that we can see an output here. I have
.DS_Store file, and the folder
images/, and it only contains one file that’s called
Okay, that’s also just a thing that we created before. Now I feel confident that I can actually delete this directory. So I’m going to say
shutil.rmtree(), and then pass in the path, which is
And it is gone, and with it, everything that was in there. Let’s check it out in the graphical user interface. So if I go back here to my home directory, you can see that the
my_folder/ that used to hang out over here is gone. And my home directory is back to its original state.
Become a Member to join the conversation.