Overwrite a File in Python

  1. Overwrite a File in Python Using the open() Function
  2. Overwrite a File in Python Using the file.truncate() Method

This tutorial will demonstrate various methods to overwrite a file in Python. We will look into methods to write new text by deleting the already saved text and how we can first read the data of the file, apply some actions and changes on it, and then overwrite it on the old data.

Overwrite a File in Python Using the open() Function

The open(file, mode) function takes file (a path-like object) as input and returns a file object as output. The file input can be a string or bytes object and contains the file path. The mode is the mode we want to open the file in; it can be r for the read mode, w for the write or a for the append mode, etc.

To overwrite a file and write some new data into the file, we can open the file in the w mode, which will delete the old data from the file.

Example code:

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

If we want first to read the data save in the file and then overwrite the file, we can first open the file in reading mode, read the data, and then overwrite the file.

Example code:

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

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

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

Since we want to read the file data first and then overwrite it, we can do so by using the file.truncate() method.

First, open the file in reading mode using the open() method, read the file data and seek to the start of the file using file.seek() method, write the new data and truncate the old data using file.truncate() method.

The below example code demonstrates how to overwrite the file using file.seek() and file.truncate() methods.

with open('myFolder/myfile.txt','r+') as myfile:
    data = myfile.read()
    myfile.seek(0)
    myfile.write('newData')
    myfile.truncate()
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python File

  • Check if a File Exists in Python
  • Read Specific Lines From a File in Python