-1

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()
Snips
  • 11
  • 1

3 Answers3

0

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!

polo-language
  • 826
  • 5
  • 13
0

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+

https://stackoverflow.com/a/2769090/17773920

Eren Temelli
  • 333
  • 1
  • 14
0

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.

Alik.Koldobsky
  • 334
  • 1
  • 10