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