Python Find and Replace Text in File Example

31-May-2023

.

Admin

Python Find and Replace Text in File Example

Hi Dev,

This article is focused on Python finding and replacing text in file examples. We will look at examples of Python find and replace in a file. This tutorial will give you a simple example of how to find and replace text in a file in Python. This article goes into detail on how to search and replace text in a file using Python. So, let's follow a few steps to create an example of a Python search and replace a string in a file.

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 a 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