How to Overwrite a File in Python

Python is extremely helpful when it comes to overwriting files, which you might have to do when you’re working with files. However, Overwriting a file is pretty useful if you want to modify the previously stored data in a file with the new one without opening it. Additionally, this page demonstrates how to safely overwrite a file in Python. Here on this page, there are following functions and methods will be demonstrated with step-by-step discussion with example code for a better understanding of the task.

  • open() and write() method
  • truncate() function approach
  • replace() approach
  • re.sub() approach

*working on Jupyter Notebook Anaconda environment Python version 3.0+.

To learn more about Python Programming, visit Python Programming Tutorials.

open() and write() syntax to overwrite file in Python

open() and write() syntax approach helps us to overwrite a file in Python in a few steps. However, If you want to bring changes to your file or overwrite the data within the file, then you can do it in a few simple steps by using the open() and write() functions. 

Here’s how the whole process executes to accomplish the task!

  • Invoke the open() method and pass two arguments in it. One is the path for the file that you want to overwrite, and the second one is the read/write syntax. Pass ‘r’ within commas if you want to read the file. However, to write the file, pass ‘w’ within the open() function. And save the results in a new variable. In our case, “file” will be the variable to read or write the file. 
  • After reading the file using the read() command.
  • Now pass the content that you want to write within the file. 
  • Using open() and write(), in the example below we pass a string. 
  • After accomplished writing content in the file, don’t forget to close the file using the close() or dot(.) operator. 
  • Initially, the file is empty, which is then replaced or overwritten by the strings that passed using the write() command. 
file=open('Data_read.txt', "r")
file.read()
file=open ('Data_read.txt', 'w')
file.write("The rabbit is the Chinese New Year's animal for 2023.")
file.close()

truncate() method to overwrite the file in Python. 

With seek(), is automatically set at the start of the file. The purpose of this is to ensure that the file starts at the beginning, thus by default, it is set to 0. Moreover, the truncate() function also overwrites or deletes the file’s content. Moreover, After invoking the seek() function, add content to the file using the write() command, which must then be truncated.

Here’s how it works!

  • Open a file from the path and pass a write command to it. 
  • Now invoke the seed() function set to zero. It will assure the file starts reading/writing from the stats.
  • Now write a file using the write() command.
  • Now call the truncate() command.
  • Now open the file and read the file. 
  • truncate() will overwrite the previous string/data from the file and replace/overwrite it with a new string/content.
file=open ('Data_read.txt', 'w')
#invoking seek() and set it to zero
file.seek(0)
file.write("flowers=Red Ginger,Tree Poppy,passion flower,water lily")
#invoke the truncate() function to overwrite a file in Python
file.truncate()
#open a file from the path
file = open('Data_read.txt', "r")
#print a modified data file
print(file.read())
flowers=Red Ginger,Tree Poppy,passion flower,water lily

replace() function to overwrite a file

replace() is the easiest approach to modifying the data in Python. Additionally, You can use replace() to Overwrite the content from some files. Here in the following example, the replace() function reads the file and searches and matches the string in the command and modified it with the new one. 

Here’s how it works!

  • Read a file using the ‘r’ command in the open() command.
  • Invoke a replace() function and overwrite a file content.
  • Don’t forget to close the file using the close() command.
  • Now again open the write and read command and print the modified file. 
  • Here in our case ‘water lily’ is replaced with ‘rose’ within the string. 
file = open("Data_read.txt", "r")
override_string = file.read()
new_content = override_string.replace('water lily', 'rose')
file.close()
Modified_file= open('Data_read.txt', 'w')
Modified_file.write(new_content)
Modified_file= open("Data_read.txt", "r")
print(Modified_file.read())
flowers=Red Ginger,Tree Poppy,passion flower,rose

re.sub() to overwrite the file data in Python

Using re.sub-method to overwrite the file data in Python. This can be done in a few easiest steps,

Here’s how it works!

  • Import a re-module from the regex() library 
  • Import Path from the pathlib module returns the file path.
  • Consider a path of the file using the Path method
  • Read a file using the rread_text() function. Files are opened, read, and closed with this function.
  • In the write_text() function, a file is opened, the text is written into it, and the file is closed.
  • write() and read() and close() the file task can be accomplished in a simple approach by using the write_text() function or read_text().
  • Now read a file and write the text into the file that you want to overwrite, do all this in re.sub() function. The function takes the old value, the new/overwrite value, and the source file variable. 
  • After doing this now read a file, print the modified version of the data, and close() the file.
# import re module
import re
from pathlib import Path
# path of the file
txt_file_path = Path("Data_read.txt")
data = txt_file_path.read_text()
txt_file_path.write_text(re.sub("passion flower", "Sun Flower", data))
# open the to 'r' the file
override_file_content = open("Data_read.txt", "r")
print(override_file_content.read())
override_file_content.close()
flowers=Red Ginger,Tree Poppy,Sun Flower,rose

Conclusion

Overwriting or modifying/deleting data from the file is a tricky task and easiest too. However, there are different approaches using various Python functions and methods are demonstrate the task using example code and step-by-step ways. Hopefully, the content on this page helps you to resolve your problem related to overwriting a file in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *