In this tutorial, we’ll try to understand how to search and replace all occurrences of a text in a file using Python in two different ways.
- Search and replace text in a different file – create a new file with matching text replaced.
- Search and replace text in the same file – modify the original file itself.
Method 1 – Search and replace text in a different file
In this method, We first open the input file in read mode and open a new file in write mode which can be used as an output file. Then read each line from the input file and replace the text with the new text and write the replaced line into the output file. Then we close both files.
Example
Now let us try to understand the above method using some worked out examples.
Example 1
input_file = open("input.txt", "rt") output_file = open("output.txt", "wt") for line in input_file: output_file.write(line.replace('Cars', 'EV')) input_file.close() output_file.close()
Steps Followed:
- Opened the input file in the read mode
- Opened a new output file in the write mode
- Loop through each line in the input file
- Replace the text in each line
- Close both the files
Initial file:

Modified file:

Method 2 – Search and replace text in the same file
In this method, We first open the input file in read mode and read all the text into a variable. Then replace all the occurrences with the new text and close the file. Then open the same file in write mode and write the replaced text into the opened file. Then close the file
Example
Now let us try to understand the above method using some worked out examples.
Example 1
input_file = open("data.txt", "rt") text = input_file.read() text = text.replace('Cars', 'Ev') input_file.close() output_file = open("data.txt", "wt") output_file.write(text) output_file.close()
Steps Followed:
- Opened the input file in the read mode
- Read all the content into a variable
- Replace the text and close the file
- Open the same file in write mode
- Write the text into the output file
- Close the file
Initial File:

Modified file:

You might also be interested in –
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.