Python Delete Files

In previous articles, we learned how to create/write data to files, read data from files. Now, we will learn how to delete or remove files in python.

 

In python, you need to import a built-in OS module to delete or remove the directory files. After importing the OS module, use the remove() function to delete the required files.

 

Following is the example of deleting the files in python.

 

import os
os.remove("testfile.txt")

Here, we considered the file (testfile.txt) exist in the same python location. If the file is in another directory, you need to mention the complete file path to delete as shown below.

 

import os
os.remove("D:\\testfile.txt ")

Check If File Already Exist

If you try to delete the file that does not exist in the directory, the OS module remove() method will throw FileNotFoundError exception. Before deleting the file, you need to verify whether the file already exists or not, as shown below.

 

import os
if os.path.exists("testfile.txt"):
    os.remove("testfile.txt")
else:
    print("File not exist")

Delete Folder

Using the python os module, you can also remove the folders, but those folders must be empty. To delete the entire folder, you need to use the os module rmdir() method as shown below.

 

import os
os.rmdir("D:\\Test")

If you try to delete the folder that contains files, you will get an exception like "The directory is not empty".

 

This is how you can delete or remove the files or folders using the python os module based on your requirements.