How to erase the file contents of text file in Python?

I have text file which I want to erase in Python. How do I do that?

Answer rating: 358

In python:

open("file.txt", "w").close()

Or alternatively, if you have already an opened file:

f = open("file.txt", "r+")
f.truncate(0) # need "0" when using r+




Get Solution for free from DataCamp guru