Overwrite a File in Python

To overwrite a file in Python use the  file.truncate() or file.write() method from the open() function. This tutorial will cover how to use both of these utilities.

 

Overwrite a File with the Python open() Function

The Python open() function will overwrite all existing data in a file. To use it, pass the file path as the first argument, set the mode as writing ('w') in the second argument then use the write() function on the file object.

 

with open('dir/file.txt', "w") as myfile:
   myfile.write(newData)

 

Overwrite a File in Python with the file.truncate() Method

Another approach is to open a file in reading + writing mode ('r+)', seek to the first line then truncate it.

 

with open('dir/file.txt','r+') as myfile:
   myfile.seek(0)
   myfile.write('newData')
   myfile.truncate()