How to Search and Replace String in txt File in Python?

01-Jun-2023

.

Admin

How to Search and Replace String in txt File in Python?

Hi Dev,

In this example, you will learn how to search and replace strings in a Txt file in Python. I would like to show you the Python search and replace it in a Txt file. this example will help you Python search and replace text files. you can understand the concept of Python search and replace line in text files.

Here, I will give you a very simple example to search and replace a string in a file using python script. we will use open() and replace() functions to find strings and replace them in a file using Python 3. So, let's see the simple example:

Example :


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

example.txt

Hi

This is example.com

This is example.com

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

main.py

findString = "example.com"

replaceString = "nicesnippets.com"

# Find Text and Replace Word

with open('example.txt', 'r') as f:

data = f.read()

data = data.replace(findString, replaceString)

with open('example.txt', 'w') as f:

f.write(data)

print("Text replaced")

Output:

Hi

This is nicesnippets.com

This is nicesnippets.com

#Python