Delete File if It Exists in Python

Python provides us with various tools to perform file handling operations. In this article, we will discuss different ways to delete file if it exists in the file system using python.

Delete File if Exists Using the os.remove() Method

You can delete a file if exists using the remove() method defined in the os module. The remove() method takes the file name as the input parameter and deletes the file.  You can delete a file by passing the filename to the remove() method as follows.

If the file name is correct, the remove() method is successfully executed. However, if the file doesn’t exist, the program runs into FileNotFoundError. You can observe this in the following example.

Output:

To avoid such a situation, you can use exception handling using the try-except blocks. Here, we will execute the remove() method in the try block and catch the FileNotFoundError exception in the except block saying that the file does not exist.

In this way, the program will delete the file only if it exists. When the file does not exist, the program will print an appropriate message and will terminate normally instead of running into the FileNotFoundError exception. You can observe this in the following example.

Output

Instead of exception handling, we can take pre-emptive measures so that the program doesn’t run into errors when the file doesn’t exist. For this, we will first check if the file is already present in the file system or not. If yes, only then, we will delete the file. 

To check if the file exists or not, we can use the os.path.exists() method. The exists() method takes the filename as its input argument and returns True if the file path exists in the file system. Otherwise, it returns False. We can use the exists() method to delete file if it exists as follows.

Using the exists() method has a major drawback. It also returns True for file paths representing directories. The remove method cannot delete a directory. Due to this, the program runs into IsADirectoryError error as shown below. 

Output:

To avoid the IsADirectoryError, we can check if a file exists or not using the os.path.isfile() method. The isfile() method takes the filename as an input string and returns True if the file exists in the file system. Otherwise, it returns False.

After checking the file if it exists or not using the isfile() method, we can delete the file using the remove method using the following code.

Output:

Instead of handing or taking preemptive action to avoid errors if the file doesn’t exist, you can also suppress the exception using the contextlib module. The contextlib module provides us with the suppress() method with which we can suppress the exceptions.

The suppress() method takes one or more exception names as input arguments and returns a context manager that suppresses the exceptions specified in the input argument. We can use the suppress() method and the with statement to delete a file only if it exists as follows.

If you use the above code, the file will be deleted if it is present in the file system. If it is not present, the program will terminate normally.

Delete File if Exists Using the os.unlink() Method  

The os.unlink() method is semantically similar to the os.remove() method. It also takes a file path as input and deletes the file if it exists as follows.

In case the file does not exist, it raises the FileNotFoundError as follows.

Output:

You can use the unlink() method to delete a file only if it exists using the try-except block in python as follows.

You can use the unlink() method with the os.path.exists() method to delete file if it exists in the file system as follows.

Similar to the remove() method, the unlink() method raises the IsADirectoryError if the file path given to the unlink() method is a directory. You can observe this in the following example.

Output:

Instead of the exists() method, you can use isfile() method with the unlink() method to delete file if it exists as shown below.

You can also use the suppress() method along with the unlink() method to delete file if it exists using python as follows.

Conclusion

In this article, we have discussed different ways to delete file if it exists using a python program. Out of all the approaches, I will suggest you use the isfile() method along with the remove() method or the unlink() method to delete a file if there is a high probability that the file doesn’t exist.

If there is a high probability that the file exists, you can use the approach with the suppress() method or try-except block.

Was this post helpful?


import_contacts

You may also like:

Related Posts

  • 25 June

    Convert Roman Number to Integer in Python

    Table of ContentsHow to Convert Roman Number to Integer in PythonHow to convert roman number to integer in python?Using the if...else statement to convert roman number to integer in Python.Using classes and a dictionary to convert roman number to integer in Python.Using the roman module to convert roman number to integer in Python.ConclusionWas this post […]

  • 11 June

    Remove Single Quotes from String in Python

    Table of ContentsRemove single quotes from string in Python.How to remove single quotes from string in Python?Using the replace() function to remove single quotes from string in Python.Using a for loop to remove single quotes from string in Python.Using the join() function to remove single quotes from string in Python.Using the re module functions to […]

  • 11 June

    Escape Backslash Character in Python

    Table of ContentsEscape backslash character in python.How to use escape backslash character in python?Using the escape backslash character in python to represent whitespace characters.Using the escape backslash character in python to turn special characters into ordinary characters.Using the escape backslash character in f-strings in Python.Using the escape backslash character in raw strings in Python.Was this […]

  • 11 June

    Remove Parentheses From String in Java

    Table of ContentsJava StringsRemove Parentheses From a String Using the replaceAll() MethodRemove Parentheses From a String by TraversingConclusionWas this post helpful? Java uses the Strings data structure to store the text data. This article discusses methods to remove parentheses from a String in Java. Java Strings Java Strings is a class that stores the text […]

  • 11 June

    Break out of function in Python

    Table of ContentsBreak out of function in PythonHow to break out of function in Python?Using the return statement to break out of function in PythonUsing the try and except block to break out of function in PythonUsing the sys.exit() function to break out of function in PythonConclusionWas this post helpful? In this post, we will […]

  • 11 June

    Check if Object Is Iterable in Python

    Table of ContentsWhat are iterables in Python?How to check if object is iterable in Python?Using the iter() function to check if object is iterable in PythonUsing the for loop to check if object is iterable in PythonUsing the isinstance() function to check if object is iterable in PythonConclusionWas this post helpful? In this post, we […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.