Python Program to Replace Text in a File

30 Nov, 2021
In this article, we are going to replace Text in a File using Python. Replacing Text could be either erasing the entire content of the file and replacing it with new text or it could mean modifying only specific words or sentences within the existing text.
In this method we replacing all the text stored in the text file, for this, we will open the file in reading and writing mode and it will rewrite all the text.
Python3
# Python program to replace text in a files = input("Enter text to replace the existing contents:")f = open("file.txt", "r+") # file.txt is an example here,# it should be replaced with the file name# r+ mode opens the file in read and write modef.truncate(0)f.write(s)f.close()print("Text successfully replaced")
Output: 
Enter text to replace the existing contents: Geeks
Text successfully replaced
The simple for loop is a conventional way to traverse through every line in the given text file and find the line we want to replace. Then, the desired line can be replaced by using the replace() function.  Finally, the file is opened in the write mode, and the replaced content is written in the given file.
Python3
# Python program to replace text in a filex = input("enter text to be replaced:")y = input("enter text that will replace:") # file.txt should be replaced with# the actual text file namef = open("file.txt", "r+") # each sentence becomes an element in the list ll = f.readlines() # acts as a counter to know the# index of the element to be replacedc = 0for i in l:    if x in i:         # Replacement carries the value        # of the text to be replaced        Replacement = i.replace(x, y)         # changes are made in the list        l = Replacement    c += 1 # The pre existing text in the file is erasedf.truncate(0) # the modified list is written into# the file thereby replacing the old textf.writelines(l)f.close()print("Text successfully replaced")
Output:
Enter text to be replaced: Geeks
Enter text that will replace: Geekforgeeks
Text successfully replaced
We use the os module to rename a new file with the original file name. In this method instead of editing the already existing file, we instead create a new file with the modified content and then delete the old file and rename the new file.
Python
# Program to replace text in a fileimport osx = input("Enter text that will replace the existing text:")f = open("file.txt", "r+")f1 = open("new.txt", "r+") f1.write(x)os.remove("file.txt")os.rename("new.txt", "file.txt")f1.close() print("File replaced")
Output:
Enter text that will replace the existing text: geeks
File replaced
The fileinput.input() method gets the file as the input line by line and is mainly utilized for appending and updating the data in the given file. The fileinput and sys module need to be imported to the current Python code in order to run the code without any errors. The following code uses the fileinput.input() function for replacing the text in a line in Python.
Python3
import sysimport fileinput x = input("Enter text to be replaced:")y = input("Enter replacement text") for l in fileinput.input(files = "file.txt"):    l = l.replace(x, y)    sys.stdout.write(l)
Output:
Enter text to be replaced: Geeks
Enter replacement text: Geeksforgeeks
surindertarika1234
sagar0719kumar
Picked
Python file-handling-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list