EN
Python - delete file
0
points
In this article, we would like to show you how to delete a file using Python.
Quick solution:
import os
os.remove("example.txt")
Practical examples
1. Delete file
In this example, we import the os
module and use os.remove()
method to delete the example.txt
file from our project.
import os
os.remove("example.txt")
or if the file is in a different location than our project we need to specify the path:
import os
os.remove("C:\\example_directory\\example.txt")
2. Safe way to delete the file
To avoid getting an error, check if the file exists first.
import os
if os.path.exists("example.txt"):
os.remove("example.txt")
else:
print("The file does not exist")