How to Overwrite a File in Python?

Python provides different functions and modules that are used to manipulate, organize and edit a file. The file manipulation includes creating, deleting, updating, and saving the file. In Python, Overwriting the file means replacing the file’s old text/data with new text/data.

Overwriting involves removing and replacing the existing file’s content with new content but the file name remains the same. Various methods in Python are used to overwrite the file. This Python blog post discusses the given below methods:

Method 1: open() Method

In Python, the open() function is used to open the file in various modes. The modes indicate the type of operations performed on the file. In the example given below, the “open()” function is used along with the “write()” function to open and overwrite the file:

The following snippet shows the original content of the “sample.txt” file:

Code:

file = open("sample.txt", "w")
file.write("Hello and Welcome!")
file.close()

In the above code:

  • The “open()” function opens the file “sample.txt” in “w” write mode and overwrites a file with new text.
  • To read the file, the “open()” function is opened in “r” mode, and the file is read using the “read()” function.

Output:

The above snippet shows that the new content has been successfully overwritten on a file named “sample.txt”.

Method 2: Using seek() and truncate() Functions

The “seek()” is used to set the pointer at the start of the program. The “truncate()” function removes the file’s data. In the example given below, the “seek()” and “truncate()” functions are used to overwrite the selected file:

The following snippet shows the original content of the “sample.txt” file:

Code:

file = open("sample.txt", "w")
file.seek(0)
file.write("Java Guide")
file.truncate()
file.close()

In the above code:

  • The “open()” function opens the file in “w” mode.
  • The “seek()” function default parameter value is set to “0” and is used to set the pointer at the start of the file.
  • The new content is overwritten to the “sample.txt” file, and the old file is truncated using the “truncate()” function.

Output:

The new content “Java Guide” has been overwritten to a file named “sample.txt”.

Method 3: Using pathlib Module and re.sub() Function

To interact with a file system in a more efficient way, the “pathlib” module is used in Python. The “re.sub()” function of the regex module replaces specific occurrences in the string. In the example below, the “pathlib” module’s function “Path” is used to overwrite the file.

The following snippet shows the original content of the “sample.txt” file:

Code:

import re
from pathlib import Path
f_path = Path("sample.txt")
file_data = f_path.read_text()
f_path.write_text(re.sub("Java", "Python", file_data))

In the above code:

  • The “pathlib” and “re” modules are imported in the program.
  • The “path” function is used to get the file’s path.
  • The file data has been read using the “read_text()” function and stored in a variable “file_data”.
  • The “re.sub()” function replaces the old content “Java” with new content “Python” by taking the value as an argument.

Output:

The above output verifies that the file has been overwritten using the “re.sub()” function.

Method 4: os.remove() Method

To interact with the operating system and perform the different operating tasks, the “os” module is used in Python. In the example given below, the “os.remove()” is used to overwrite the file in Python:

The following snippet shows the original content of the “sample.txt” file:

Code:

import os
if (os.path.exists("sample.txt")):
    os.remove("sample.txt")
else:
    print("File Does Not Exists")
new_file = open("sample.txt", "w")
new_file.write('Linux/Ubuntu Best Online Guide')
new_file.close()

In the above code:

  • The “os.remove()” function removes the file if the file is already present in the given path.
  • After checking the file’s existence, the next step is to open the file in write mode.
  • The “write()” function overwrites the file “sample.txt” with new content.

Output:

The above snippet shows that the file has been overwritten successfully.

Method 5: Replace() Function

To replace the specified phrase with another specific phrase, the “replace()” function is used in Python. In the example given below, the “replace()” method is used to overwrite the file:

The following snippet shows the original content of the “sample.txt” file:

Code:

#reading data from file
file = open("sample.txt", "r")
data = file.read()

#writing replaced data to file data = data.replace('Linux', 'Ubuntu 22.04')
file.close()

file1 = open('sample.txt', 'w')
file1.write(data)
#displaying data
file1 = open("sample.txt", "r")
print(file1.read())

In the above code:

  • The file is opened in reading “r” mode, and the data of the file is read and stored in a variable “data”.
  • The “replace()” function replaces the old values “Linux” with the new ones “Ubuntu 22.04”.
  • To write the replaced data, we need to open the file again in write “w” mode and write the data using the “write()” function.

Output:

The above snippet shows that the new data has been overwritten on a file named “sample.txt”.

Method 6: fileinput.input() Method

The “input()” function of the “fileinput” module is used to update the file or append the data to the file. In the example given below, the “fileinput.input()” function is used to overwrite the file:

The following snippet shows the original content of the “sample.txt” file:

Code:

import fileinput
for line in fileinput.input("sample.txt", inplace=True):
    print(line.replace("Java", "Python"), end='')

In the above code:

  • The “for loop” is used along with the “fileinput” module function “fileinput.input()” to overwrite the file.
  • The “replace()” function is utilized to replace the specific line of a file named ”sample.txt”.

Output:

As can be seen from the above snippet, the file has been successfully overwritten.

Conclusion

To overwrite a file in Python, the “open()” method, “seek() and truncate()”, “re.sub()”, “os.remove()”, “replace()”, and “fileinput()” methods are used. The “open()” method is opened in write mode to overwrite the file in Python. The “os.remove()” function is also used to overwrite the file in Python. This article presented a detailed guide on overwriting the file in Python.