I would like to delete all the contents of my file first, then write on it. How do I do that with a simple file? `
fileHandle = open("file.txt","w")
fileHandle.write(randomVar)
fileHandle.close()
I would like to delete all the contents of my file first, then write on it. How do I do that with a simple file? `
fileHandle = open("file.txt","w")
fileHandle.write(randomVar)
fileHandle.close()
What you need is to open the file in a truncating mode. These are "w" and "w+". Your current code uses "w", so it should work fine!
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+
whenever using open(filename,'w')
all the content of the data will be overwritten.
If you wish to add content to the file you should be using open(filename,'a')
.
In addition, I would recommend opening the file using
with open('filename','mode') as f: your code here
as it will provide context manager, making sure the file will closed when you are done with it.