In this article, we have presented the approach to delete a file in Python. We have used the os library.
Table of contents:
- Delete file in Python
- Complete Code
Delete file in Python
To delete a file in Python, we will use the os module so we need to import it.
One can delete a file using the remove() function of os. The specified file will be deleted if it exists.
If the file does not exist, then the above function will throw an error. To tackle this, we need to check if the file exists first and then, act accordingly. One can check if a file exists using os.path.exists() function.
if os.path.exists("file.txt"): os.remove("file.txt")
Following is the complete Python code to a delete file:
import os if os.path.exists("file.txt"): os.remove("file.txt") print ("File deleted") else: print ("File does not exist")
With this article at OpenGenus, you must have the complete idea of how to delete a file in Python.