Overwrite a File in Python
-
Overwrite a File in Python Using the
open()
Function -
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 the file.seek()
method, write the new data and truncate the old data using the 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()
Syed Moiz is an experienced and versatile technical content creator. He is a computer scientist by profession. Having a sound grip on technical areas of programming languages, he is actively contributing to solving programming problems and training fledglings.
LinkedInRelated Article - Python File
- Get All the Files of a Directory
- Append Text to a File in Python
- Check if a File Exists in Python
- Find Files With a Certain Extension Only in Python
- Read Specific Lines From a File in Python
- Check if File Is Empty in Python