Overwrite a File in Python

Python

In this post, we are going to learn about how to Overwrite a File in Python with code examples and also learned how to replace the contents of files instead of overwriting.

Ways to overwrite a file in Python


  • File.open() method
  • File.truncate() method
  • Replace string in file in Python

1. File.open() method to Overwrite a File in Python


The File. open(filepath, mode) method is used to open a file in a given mode. if we open a file in write mode(w) then it will overwrite the file.,If the file already exists.

  • filepath : is the file name along with path that we want to overwrite.
  • mode:The second argument is an important argument as it decides the mode in which we are trying to open/create the file.

Python Program to overwrite a file using write mode

with open("samplefile.txt","w") as file:
 file.write("this is sample file\n")
 file.write("Welcome to devenum \n")
 file.close()


2. File.truncate() method to Overwrite a File in Python


Sometimes it needs to read the file first and after we want to overwrite it. By using the File.truncate() method we can achieve this.

In this below example, we are opening a file in read mode (r+). “+” will open a file for reading and writing both at the same time.

Step to Overwrite a File using File.truncate() method

  • The file.seek(0) method is used to change position of file handle to gievn position the default value is 0.
  • by using the write() method we are writing contents to file.
  • The file.truncate() method to truncate the contents that already exist in file.

Python Program to overwrite a file

with open("samplefile.txt","r+") as file:
    data = file.read()
    file.seek(0)
    file.write('Welcome to devenum')
    file.truncate()

3. Replace string in file in Python


In this example, we are replacing the existing contents of the file with new content. We are opening the file using open() method in reading mode. Reading all contents of the file and calling the replace() method to replace the existing contents with new contents.

Secondly, open the file in write mode and write the replaced contents.

Python Program to Replace string in file

with open("samplefile.txt", 'rt') as file:
    content = file.read()
   
    content = content.replace('welcome', 'Good Morining!')



with open("samplefile.txt", 'wt') as file:

  file.write(content)

Output

Good Morining! to devenum

Summary

In this post, we have learned how to Overwrite a File in Python with code examples and also learned how to replace the contents of files instead of overwriting.

Ways to overwrite a file in Python

  • File.open() method
  • File.truncate() method
  • Replace string in file in Python