How to Overwrite a file in Python

Hey geek! in this tutorial we are going to learn how to overwrite a file in Python.

There are many ways where we can Overwrite a file in Python. We are going to use some simple methods for overwriting a file in Python.

Overwriting a file using seek() and truncate() method

Using file.seek() and file.truncate() method we can overwrite the Python file.

First, we need to open the file where we want to overwrite the file, but we need to open the file only in the read mode and by using seek() method which is used to change the position of the filehandle to a specified position.

Next, write the new data and then use the truncate() method for removing old data.

 Python code for overwriting a file

with open('myFolder/myfile.txt','r+') as myfile:
    data = myfile.read()
    myfile.seek(0)
    myfile.write('newData')
    myfile.truncate()

By implementing the above code, we can overwrite the file in Python using truncate() and seek() methods.

Overwriting a file using open() and write() methods in Python

Likewise, truncate() and seek() method we can overwrite a file using open() and write() methods too.

The open() method consists of two parameters first one is a file, as input, moreover called a path which returns a file object as output.

The second parameter is the mode, whether to open the file in reading mode ‘r’, write mode ‘w’, append mode ‘a’, etc.

Firstly, if we want to read the file and then overwrite it, we need to open the file in reading mode and then overwrite it.

Python code using this method

with open('downloads/myfile.txt', "r") as myfile:
    data = myfilef.read()

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

In the above code, after reading the file, the new data is to be entered. Both the above methods are equally important, learning both of them might be useful.

Finally, using the above methods we can overwrite a file in Python. That’s it for this tutorial guys. I think this article has helped you in some way.

Thank you

Keep Coding, Keep learning!

Similarly, check the below articles on your interest

Leave a Reply

Your email address will not be published.