Deleting a File
I just again cleared the screen and did the imports again so that we have a bit more screen real estate to work with. The next task is to delete the file
We can do that, right? Where is
file1.txt again? Hmm. I will just start by listing the contents of
and for this, I can use
.iterdir() and put it into the
list() function just to display the results. Okay, so I have
file1, all right, so it’s in here.
I do have
file1 in here, and I want to get rid of it. So first, I will need the path. This path, I need to get it. Probably the most readable way to get the path to
file1.txt in here is going to be to say
file1 = my_folder and then
And that should be the same path as we have here on position one. Let’s double-check with a little, having a little fun with Python on the side, so I’m going to say
list(my_folder.iterdir()), and I want the second element in here.
01:28 Let me copy that and see whether we’re getting the right result.
file1.txt, and I can also compare whether it’s the same to
file1, and we got the right path. Okay, perfect. So,
file1 points to a file that exists inside of
Now I want to delete this, and I can do it by saying
02:01 Again, Python doesn’t really give me a feedback here whether or not this worked. You’ll see that if I run it and the file doesn’t exist, it actually gives me feedback and tells me that this file doesn’t exist.
So by not giving us feedback here, we know that it should have worked out. Let’s double-check, though, by doing the
and there it is. It’s gone. Not here anymore. And of course, we want to go double-check in the graphical user interface again. So if I head over here and go back to
my_folder/, now there’s another gaping hole where
file1.txt used to be, so we successfully deleted it. Awesome.
02:48 We’re approaching the end of those exercises. The next one is already number five, and let’s tackle it in the next lesson.
Become a Member to join the conversation.