Table of Contents
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.
1 2 3 4 5 6 |
import os os.remove("output.txt") |
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.
1 2 3 4 5 6 |
import os os.remove("output.txt") |
Output:
1 2 3 4 5 6 7 8 |
/usr/lib/python3/dist-packages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.7) or chardet (3.0.4) doesn't match a supported version! warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported " Traceback (most recent call last): File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 3, in <module> os.remove("output.txt") FileNotFoundError: [Errno 2] No such file or directory: 'output.txt' |
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.
1 2 3 4 5 6 7 |
import os try: os.remove("output.txt") except FileNotFoundError: print("File is not present in the system.") |
Output
1 2 3 |
File is not present in the system. |
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.
1 2 3 4 5 6 7 8 |
import os if os.path.exists("output.txt"): os.remove("output.txt") else: print("File is not present in the system.") |
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.
1 2 3 4 5 6 7 8 |
import os if os.path.exists("/home/aditya1117/linear regression in python/"): os.remove("/home/aditya1117/linear regression in python/") else: print("File is not present in the system.") |
Output:
1 2 3 4 5 6 7 8 9 |
/usr/bin/python3.8 /home/aditya1117/PycharmProjects/pythonProject/string1.py /usr/lib/python3/dist-packages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.7) or chardet (3.0.4) doesn't match a supported version! warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported " Traceback (most recent call last): File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 3, in <module> os.remove("/home/aditya1117/linear regression in python/") IsADirectoryError: [Errno 21] Is a directory: '/home/aditya1117/linear regression in python/' |
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.
1 2 3 4 5 6 7 8 |
<><code>import os if os.path.isfile("/home/aditya1117/linear regression in python/"): os.remove("/home/aditya1117/linear regression in python/") else: print("File is not present in the system.") |
Output:
1 2 3 |
File is not present in the system. |
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.
1 2 3 4 5 6 7 8 |
import contextlib import os with contextlib.suppress(FileNotFoundError): os.remove("output.txt") |
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.
Further reading:
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.
1 2 3 4 5 |
import os os.unlink("output_file.txt") |
In case the file does not exist, it raises the FileNotFoundError
as follows.
1 2 3 4 5 |
import os os.unlink("output_file.txt") |
Output:
1 2 3 4 5 6 7 8 |
/usr/lib/python3/dist-packages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.7) or chardet (3.0.4) doesn't match a supported version! warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported " Traceback (most recent call last): File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 3, in <module> os.unlink("output_file.txt") FileNotFoundError: [Errno 2] No such file or directory: 'output_file.txt' |
You can use the unlink()
method to delete a file only if it exists using the try-except block in python as follows.
1 2 3 4 5 6 7 8 |
import os try: os.unlink("output_file.txt") except FileNotFoundError: print("File is not present in the system.") |
You can use the unlink()
method with the os.path.exists()
method to delete file if it exists in the file system as follows.
1 2 3 4 5 6 7 |
import os if os.path.exists("output_file.txt"): os.unlink("output_file.txt") else: print("File is not present in the system.") |
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.
1 2 3 4 5 6 7 |
import os if os.path.exists("/home/aditya1117/linear regression in python/"): os.unlink("/home/aditya1117/linear regression in python/") else: print("File is not present in the system.") |
Output:
1 2 3 4 5 6 7 8 |
/usr/lib/python3/dist-packages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.7) or chardet (3.0.4) doesn't match a supported version! warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported " Traceback (most recent call last): File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 3, in <module> os.unlink("/home/aditya1117/linear regression in python/") IsADirectoryError: [Errno 21] Is a directory: '/home/aditya1117/linear regression in python/' |
Instead of the exists()
method, you can use isfile()
method with the unlink()
method to delete file if it exists as shown below.
1 2 3 4 5 6 7 |
import os if os.path.isfile("/home/aditya1117/linear regression in python/"): os.unlink("/home/aditya1117/linear regression in python/") else: print("File is not present in the system.") |
You can also use the suppress()
method along with the unlink()
method to delete file if it exists using python as follows.
1 2 3 4 5 6 7 8 |
import contextlib import os with contextlib.suppress(FileNotFoundError): os.unlink("output_file.txt") |
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.