Delete file in Python

In this article, we have presented the approach to delete a file in Python. We have used the os library.

Table of contents:

  1. Delete file in Python
  2. Complete Code

Delete file in Python

To delete a file in Python, we will use the os module so we need to import it.

import os

One can delete a file using the remove() function of os. The specified file will be deleted if it exists.

os.remove("file.txt")

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")

Complete Code

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.