Python Program to Replace Text in a File
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.
Method 1: Removing all text and write new text in the same file
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.
Enter text to replace the existing contents: Geeks Text successfully replaced
Method 2: Using Replace function in for loop
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.
Enter text to be replaced: Geeks Enter text that will replace: Geekforgeeks Text successfully replaced
Method 3: Using the OS module to replace the file with new text
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.
Enter text that will replace the existing text: geeks File replaced
Method 4: Using fileinput.input()
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.
Enter text to be replaced: Geeks Enter replacement text: Geeksforgeeks