Delete File in Python
To delete a file in Python, we can import
os package and use
remove() function of the
In this tutorial, we will learn how to delete a file using Python programming.
First we shall look into the syntax of os.remove() function. Secondly, we shall look into examples, where we actually delete a file. The examples cover scenarios: delete file without checking if it is actually present; delete file with a prior check if the file is present.
The syntax of os.remove() function is:
os.remove() deletes the file present at the location provided by String value
os.remove() deletes the file if it is present. If the file is not present, nothing happens, not even an error occurs. The execution continues with subsequent program statements. So, it is recommended that you check if the file is present, if you would like to be sure if you have actually deleted the file.
Example 1 – Delete File in Python
In the following Python program, we are deleting a file present at the location
import os #delete the file os.remove("D:/data.txt") print('The file is deleted.')
The file is deleted.
Example 2 – Delete File in Python if Present
You can make a check if file is present, prior to the deletion and make sure, if you have actually deleted the file.
To check if the file is present, use os.path.isfile() function. os.path.isfile() function returns true if file is present in the storage. Else the function returns false.
Once we are sure that the file is present, then we can call the function os.remove() to delete the file.
import os file_path = "D:/data.txt" #check if file is present if(os.path.isfile(file_path)): #delete the file os.remove(file_path) print('The file is deleted.') else: print('The file is not present.')
If the file is present and deleted, you would get the following output.
The file is deleted.
If the file is not present, and you try to delete, you get the following output.
The file is not present.
In this Python Tutorial, we learned how to delete a file programmatically using Python.