How to Delete File If Exists in Python?

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
    print("The file has been deleted successfully!")
    print("Can not delete the file as it doesn't exists")

Delete Folder

To delete an entire folder, use the os.rmdir() method:

import os

Also Read This ๐Ÿ‘‰   hex to rgb - How to convert hex to RGB and RGB to hex in Python?