ItSolutionStuff.com

How to Find and Replace Text in a File in Python?

By Hardik Savani • October 30, 2023
Python

Hey Friends,

In this short tutorial, we will cover a python find and replace in file. This example will help you how to find and replace text in file in python. I explained simply about how to search and replace text in a file using python. I explained simply about python search and replace string in file.

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:

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 = "itsolutionstuff.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:

example.txt

Hi
This is itsolutionstuff.com
This is itsolutionstuff.com

I hope it can help you...

Tags: Python
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Set and Get Environment Variables in Python?

Read Now →

Python Generate Random Number Between 0 to 1 Example

Read Now →

Python Create PDF File from Text Example

Read Now →

Python Read Text File into List Example

Read Now →

How to Read Text File Line by Line in Python?

Read Now →

How to Read a Text File in Python?

Read Now →

How to Append Text or Lines to a Text File in Python?

Read Now →

Python Generate Text File from List Example

Read Now →

Python List Print All Elements Except First Example

Read Now →

How to Convert List to Lowercase in Python?

Read Now →

Python Delete Folder and Files Recursively Example

Read Now →

Python Post Request with Bearer Token Example

Read Now →

Python POST Request with Parameters Example

Read Now →