Python Search and Replace String in txt File Example

By Hardik Savani October 30, 2023 Category : Python

Hi Dev,

Now, let's see an example of python search and replace in txt file. We will look at an example of python search and replace in text file. If you have a question about python search and replace line in text file then I will give a simple example with a solution. you can see find and replace in text file python.

Here, i will give you a very simple example to search and replace string in file using python script. we will use open() and replace() function to find string and replace in file using python 3. so, let's see the simple example:


Here, we will create an "example.txt" file as like below:


This is
This is

Now, we will create file and find string from that file as like the below code:

findString = ""
replaceString = ""
# Find Text and Replace Word
with open('example.txt', 'r') as f:
    data =
    data = data.replace(findString, replaceString)
with open('example.txt', 'w') as f:
print("Text replaced")



This is
This is

I hope it can help you...

Tags :