- How to Delete File If Exists in Python
- Method 1: Using the os.remove() along with os.path.exists() function
- Example
- Error handling in os.remove()
- Method 2: Using the os.ulink() function
- Syntax
- Parameters
- Example
- Python : How to remove a file if exists and handle errors | os.remove() | os.ulink()
- How to remove a file using os.remove()
- Frequently Asked:
- Remove a file if exists using os.remove()
- Remove a file using os.ulink()
- Related posts:
- Share your love
- Leave a Comment Cancel Reply
- Terms of Use
- Disclaimer
- Delete File if It Exists in Python
- Delete File if Exists Using the os.remove() Method
- How To Delete and Remove File and Directory with Python?
- Check If File or Directory Exist
- Remove File with remove() Method
- Handle Exceptions and Errors For File Delete Operation
- Remove File with unlink
- Remove Empty Directory/Folder with rmdir() Mehtod
- Delete Directory and Contents Recursively with rmtree() Method
- Delete Only Specific File Types or Extensions
How to Delete File If Exists in Python
Here are two ways to delete a file if it exists in Python.
- Using the “os.remove()” along with “os.path.exists()” function
- Using the “os.ulink()” method
Method 1: Using the os.remove() along with os.path.exists() function
To delete a file if it exists in Python, you can use the os.remove() function along with the os.path.exists() to check if the file exists before attempting to remove it.
Example
import os if os.path.exists("app.cpp"): os.remove("app.cpp") print("The file has been deleted successfully") else: print("The file does not exist!")
The file has been deleted successfully
The file is there; that’s why it was successfully deleted.
If you try to execute the above script again, you will get the following output.
Before removing the file, it checks if it exists; in our case, it does not. So, it returns the “File does not exist!” output.
Error handling in os.remove()
The os.remove() function can throw an OSError if,
- A file doesn’t exist at the given path. An error message will be thrown, which we have already seen.
- The user doesn’t have access to the file at the given path.
- Passing the directory to the os.remove() function will throw the error.
Method 2: Using the os.ulink() function
Python os.ulink() function can be used to remove a file.
Syntax
Parameters
filePath: The unlink() function takes a filePath as an argument which is the file to the path.
Example
I have created an app.cpp file in the current directory.
import os # Handle errors while calling os.ulink() try: os.ulink("app.cpp") except: print("Error while deleting file")
If the file exists, then it will remove the file. If it does not, it will execute the except block, which prints “Error while deleting file”.
That is pretty much it for removing a file if it exists in Python.
Python : How to remove a file if exists and handle errors | os.remove() | os.ulink()
In this article we will discuss how to remove a file if only it exists and how to handle other types of exceptions using os.remove() & os.ulink().
How to remove a file using os.remove()
python ‘s os module provides a function to remove the file i.e.
It accepts the file path as argument and deletes the file at that path. File path can be relative to current working directory or an absolute path.
Frequently Asked:
import os # Remove a file os.remove('/home/somedir/Documents/python/logs')
It will delete the file at given path.
Error handling in os.remove()
os.remove() can throw OSError if,
- A file don’t exists at given path. Error message will be like,
- [WinError 2] The system cannot find the file specified
- FileNotFoundError: [Errno 2] No such file or directory
- [WinError 5] Access is denied
- IsADirectoryError: [Errno 21] Is a directory
Therefore it’s always good to check for errors while calling os.remove() i.e.
Remove a file if exists using os.remove()
As os.remove() can throw OSError if given path don’t exists, so we should first check if file exists then remove i.e.
import os filePath = '/home/somedir/Documents/python/logs'; # As file at filePath is deleted now, so we should check if file exists or not not before deleting them if os.path.exists(filePath): os.remove(filePath) else: print("Can not delete the file as it doesn't exists")
But still if the given file path points to a directory instead of file or user don’t have access to the given file, then os.remove() can still throw error.
Therefore, best way is to use try catch while calling os.remove() i.e.
import os # Handle errors while calling os.remove() try: os.remove(filePath) except: print("Error while deleting file ", filePath)
Remove a file using os.ulink()
python provides an another function in os module to remove files i.e.
It’s exactly similar to os.remove(). Example,
import os # Handle errors while calling os.ulink() try: os.ulink(filePath) except: print("Error while deleting file ", filePath)
Complete example is as follows,
import os def main(): filePath = '/home/somedir/Documents/python/logs/sample.log'; # Remove a file os.remove('/home/somedir/Documents/python/logs/sample.log') FileNotFoundError # As file at filePath is deleted now, so we should check if file exists or not not before deleting them if os.path.exists(filePath): os.remove(filePath) else: print("Can not delete the file as it doesn't exists") # Handle errors while calling os.remove() try: os.remove(filePath) except: print("Error while deleting file ", filePath) # Handle errors while calling os.ulink() try: os.ulink(filePath) except: print("Error while deleting file ", filePath) if __name__ == '__main__': main()
Related posts:
Share your love
Leave a Comment Cancel Reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Terms of Use
Disclaimer
Copyright © 2023 thisPointer
To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
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.
/ 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!
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.
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.
How To Delete and Remove File and Directory with Python?
Python provides different methods and functions in order to remove files and directories. As python provides a lot of functionalities we can remove files and directories according to our needs. For example, we can remove files those sizes are bigger than 1 MB.
Check If File or Directory Exist
Before removing a file or directory checking if it exist is very convenient way. We can check a file is exist with the exists() function of the os.path module. In the following example we will check different files for their existence.
import os
if os.path.exists("test.txt"):
print("test.txt exist")
else:
print("test.txt do NOT exist")
test.txt exist
status = os.path.exists("test.txt")
#status will be True
status = os.path.exists("text.txt")
#status will be False
status = os.path.exists("/")
#status will be True
status = os.path.exists("/home/ismail")
#status will be TrueRemove File with remove() Method
We can use os.remove() function in order to remove a file. We should import the os module in order to use remove function. In this example, we will remove the file named trash .
import os
os.remove("/home/ismail/readme.txt")
os.remove("/home/ismail/test.txt")
os.remove("/home/ismail/Pictures")
#Traceback (most recent call last):
# File "", line 1, in
#IsADirectoryError: [Errno 21] Is a directory: '/home/ismail/Pictures'We can see that when we try to remove a directory or folder named “Pictures” we get an error because the remove() method can not be used for removing or deleting directory or folders.
If the specified file is not exist the FileNotFoundError will be thrown as an exception. Another error or exception is if the current user do not have rights to delete file running remove() function will throw the PermissionError . In order to handle this type of errors and exceptions we should use a try-catch mechamism and handle them properly.
Handle Exceptions and Errors For File Delete Operation
We can handle previously defined errors and exceptions with the try-catch block. In this part we will hand different exceptions and errors related IsADirectory , FileNotFound , PermissionError .
We can in the above that every remote operations created an error or exception. Now we we will handle all these exception properly and print some information about the exceptions.
import os
try:
os.remove("/home/ismail/notexist.txt")
except OSError as err:
print("Exception handled: ".format(err))
# Exception handled: [Errno 2] No such file or directory: '/home/ismail/notexist.txt'
try:
os.remove("/etc/shadow")
except OSError as err:
print("Exception handled: ".format(err))
#Exception handled: [Errno 13] Permission denied: '/etc/shadow'
try:
os.remove("/home/ismail/Pictures")
except OSError as err:
print("Exception handled: ".format(err))
#Exception handled: [Errno 21] Is a directory: '/home/ismail/Pictures'Remove File with unlink
unlink is used to remove files. unlink implements exact mechanisms of the remove . unlink is defined because of to implement Unix philosophy. Look remove for more information.
Remove Empty Directory/Folder with rmdir() Mehtod
As we know Linux provides rmdir command which used to remove empty directories. Python provides the same function under os module. We can only delete empty directories with rmdir .
import os os.rmdir("/home/ismail/data")
Delete Directory and Contents Recursively with rmtree() Method
How can we delete the directory and its contents? We can not use rmdir because the directory is not empty. We can use shutil module rmtree function.
import shutil shutil.rmtree("/home/ismail/cache")
Delete Only Specific File Types or Extensions
While deleting files we may require only delete specific file types or extensions. We can use * wildcard in order to specify file extensions. For example, in order to delete text files, we can specify the *.txt extension. We should also use glob module and functions to create a list of files.
In this example, we will list all files with extensions .txt by using glob function. We will use the list name filelist for these files. Then loop over the list to remove files with remove() function one by one.
import glob import os filelist=glob.glob("/home/ismail/*.txt") for file in filelist: os.remove(file)