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.
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.
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.
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.
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.