Delete File if It Exists in Python
In Python, there is the built-in function dir() to list the contents of a directory. If a file named “file.txt” exists in the current directory, the dir() function returns a list of three items: the file’s name, the file’s size, and the file’s content.
If you want to delete a file if it exists, you can use the Python delete function. The delete function takes two arguments: the file to delete and the filename of the file to replace it with if the file is deleted.
Python Delete File if Exists Example
exists() will check file is exists or not.
remove() will delete file from path.
Here is an example of how to use the delete function to delete a file if it exists:
import os filePath = 'files/pakainfo.png'; # Check File is exists or Not if os.path.exists(filePath): # Delete File code os.remove(filePath) print("The file has been deleted successfully!") else: print("Can not delete the file as it doesn't exists")
To delete an entire folder, use the os.rmdir() method:
import os os.rmdir("myfolder")