The glob module provides a method which is also named as glob and takes the pattern string as the argument. We’ll use another Python’s inbuilt module named glob to search for the files and to iterate over them. To delete multiple files, you either use the same method multiple times or if you want to delete files having names matching with a particular patter or you simply want to delete all files inside a folder, you can loop through those files using different methods and then can use the os.remove() method inside the loop block.
In the other approach using the Try Except, it will first try to delete the file and if the error will be raised it, will run the code of the except block. You can clearly see that as the file hello1.txt exists, it has been deleted successfully while on the other hand hello2.txt does not exist and therefore the print statement written inside the else block is executed. The following python code illustrates the same. It returns True if the file exists and False if it does not.Īs it returns a boolean value, you can make use of the If-else statements to use this method along with the os.remove() method to delete a file only after checking if it actually exists or not.Įxample. The method is os.path.exists("file-path/file.extension") and it takes the file path as the string argument and returns a boolean value i.e.
The os module itself provides another method to check if a file exists or not. There’s one more way to check if a file exists before running the command to delete it.
Therefore, you must always handle such exception raising code using Try Except in python.
Our file hello.txt was in the same directory as of the currently executing python file, so we needed not to specify the full path here.Īlso, in case the remove() method does not find the file requested to delete, it will raise FileNotFoundError. You must specify the relative or full path. This way, you can delete any existing file in the specified directory. As the program completes its execution without any errors, therefore, the file hello.txt has been deleted successfully.