This post will discuss how to delete a file in Python.

1. Using os.remove() function

The standard solution to delete a file in Python is using the os.remove() function. It accepts a path that should be a file; otherwise, an exception is raised.

 
To handle the case when the specified path is a directory, you should either:

1. Check for the existence of the file before deleting it:

Download Code

 
2. Catch exception with try-except:

Download Code

Alternatively, you can use the os.unlink() function to delete a file which is semantically identical to os.remove() function.

Download Code

Starting with Python 3.4, consider using the Path.unlink() function from the pathlib module to remove a file or symbolic link.

That’s all about deleting a file in Python.