File handling is one of the first tasks we do while working with data in python. Sometimes, we need to change the contents of the original file or completely overwrite it. This article discusses different ways to overwrite a file in python.
Overwrite a File Using open() Function in Write Mode
To overwrite a file in python, you can directly open the file in write mode. For this, you can use the open()
function. The open()
function takes a string containing the file name as its first input argument and the python literal “w” as its second input argument.
If the file with the given name doesn’t exist in the file system, the open()
function creates a new file and returns the file pointer. If the file is already present in the system, the open()
function deletes all the file contents and returns the file pointer.
Once we get the file pointer, we can write the new data to the file using the file pointer and the write()
method. The write()
method, when invoked on the file pointer, takes the file content as its input argument and writes it to the file. Next, we will close the file using the close()
method. After this, we will get the new file with overwritten content.
For instance, suppose that we want to overwrite the following text file in python.
To overwrite the above file, we will use the following code.
file=open("example.txt","w")
newText="I am the updated text from python program."
file.write(newText)
file.close()
The text file after execution of the above code looks as follows.
In this example, we have directly opened the text file in write mode. Due to this, the original content of the file gets erased. After this, we have overwritten the file using new text and closed the file using the close()
method.
Using Read Mode and Write Mode Subsequently
In the above example, we cannot read the original file contents. If you want to read the original file contents, modify it and then overwrite the original file, you can use the following steps.
- First, we will open the file in read mode using the
open()
function. Theopen()
function will return a file pointer after execution. - Then, we will read the file contents using the
read()
method. Theread()
method, when invoked on the file pointer, returns the file contents as a string. - After reading the file contents, we will close the file using the
close()
method. - Now, we will again open the file, but in write mode.
- After opening the file in write mode, we will overwrite the file contents using the
write()
method. - Finally, we will close the file using the
close()
method.
After executing the above steps, we can overwrite a file in python. You can observe this in the following example.
file=open("example.txt","r")
fileContent=file.read()
print("The file contents are:")
print(fileContent)
file.close()
file=open("example.txt","w")
newText="I am the updated text from python program."
file.write(newText)
file.close()
Output:
The file contents are:
This a sample text file created for pythonforbeginners.
In this example, we first opened the file in read mode and read the contents as shown above. Then, we overwrote the file contents by opening it again in write mode. After execution of the entire code, the text file looks as shown below.
Although this approach works for us, it is just a workaround. We aren’t actually overwriting the file but reading and writing to the file after opening it separately. Instead of this approach, we can use the seek()
and truncate()
methods to overwrite a file in python.
Overwrite a File Using seek() and truncate() Method in Python
To overwrite a file in a single step after reading its contents, we can use the read()
, seek()
truncate()
and write()
methods.
- When we read the contents of a file using the
read()
method, the file pointer is moved to the end of the file. We can use theseek()
method to again move to the start of the file. Theseek()
method, when invoked on the file pointer, takes the desired position of the file pointer as its input argument. After execution, it moves the file pointer to the desired location. - To remove the contents of the file after reading it, we can use the
truncate()
method. Thetruncate()
method, when invoked on a file pointer, truncates the file. In other words, it removes all the file contents after the current position of the file pointer.
To overwrite a file in python using the seek()
and truncate()
methods, we can use the following steps.
- First, we will open the file in append mode using the
open()
function. - Next, we will read the file contents using the
read()
method. - After reading the file contents, we will move the file pointer to the start of the file using the
seek()
method. For this, we will invoke theseek()
method on the file pointer with 0 as its input. The file pointer will be moved to the first character in the file. - Next, we will use the
truncate()
method to delete all the contents of the file. - After truncating, we will overwrite the file with new file contents using the
write()
method. - Finally, we will close the file using the
close()
method.
After executing the above steps, we can easily overwrite a file in python. You can observe this in the following example.
file=open("example.txt","r+")
fileContent=file.read()
print("The file contents are:")
print(fileContent)
newText="I am the updated text from python program."
file.seek(0)
file.truncate()
file.write(newText)
file.close()
Output:
The file contents are:
This a sample text file created for pythonforbeginners.
After execution of the above code, the text file looks as follows.
Conclusion
In this article, we discussed different ways to overwrite a file in python. To learn more about python programming, you can read this article on how to convert a pandas series into a dataframe. You might also like this article on how to read a file line by line in python.
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy Learning!
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.