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 File

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

00:12 We can do that, right? Where is file1.txt again? Hmm. I will just start by listing the contents of my_folder/,

00:24 and for this, I can use .iterdir() and put it into the list() function just to display the results. Okay, so I have file2 file1, all right, so it’s in here.

00:37 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 "file1.txt".

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

01:33 Yeah, that’s 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 my_folder/.

01:51 Now I want to delete this, and I can do it by saying file1.unlink().

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.

02:12 So by not giving us feedback here, we know that it should have worked out. Let’s double-check, though, by doing the list(my_folder.iterdir()) again,

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