How to Delete Files in Python
In this lesson, we're gonna see how we can remove a file from the file system using Python.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

So far, we've seen how we can create files, how we can add to them, how we can search for them, and now we can see how we can delete them. So I have a file here that I want to get rid of called file_to_be_deleted.txt and let me just add some content just so we can prove that it's actually there, so I've some content called by here.

Now, in the file itself, what we can do is we can import the os module. So I'm gonna say import os which is short for operating system and what this allows us to do is to interact with the file system of whatever operating system we're working on. So this is a very powerful module and in this case, we're gonna use the remove method.

I'm gonna say os.remove and then provide the path for the file that we want to remove. So in this case, because we are gonna call this file or we're gonna call this script from the root of our program which means we're not in the file section directory, I have to declare the file-section path and then the path to the file, in this case, it's called file_to_be_deleted.txt.

Your file can be whatever you want to name it and that is all that we need to have there and then from that point, I'm just going to print it out and I'll say File removed. So let's test this out, we already saw that that file exists. Now let's come down and let's call this file, so python and this is in the file-section and 03_delete_file. If I run this, you can see it says File removed.

large

If I switch up and open up the operating system, I can hit refresh here and you'll see that that file is no longer there.

large

So that is all you need to do in order to delete files in Python.

Code

import os

os.remove("file-section/file_to_be_deleted.txt")

print("File Removed!")