Delete a file in Python

To delete a file in Python we use the remove function.

ยป More Python Examples

# geekole.com
from os import remove
remove('/home/geekole/Documents/python/files/filename.txt')

If you run the code, the file whose path you type as an argument disappears.

Delete a file in Python

If the file does not exist, an error will be generated and you may need to verify that it exists before using remove, with the function path.exists(“/path/filename.txt”).

# geekole.com
from os import remove
from os import path
if path.exists("/home/geekole/Documents/python/files/filename.txt"):
    remove('/home/geekole/Documents/python/files/filename.txt')

We hope this example of how to delete a file in Python will be useful to you.