Python Search and Replace String in txt File Example
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:
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Python Read Text File into List Example
- How to Read Text File Line by Line in Python?
- How to Read a Text File in Python?
- How to Append Text or Lines to a Text File in Python?
- Python Generate Text File from List Example
- Python Create Text File If Not Exists Example
- Python Create Text File in Specific Directory Example
- How to Create Multiline Text File in Python?
- Python Delete Directory if Exists Example
- Python Delete File if Exists Example
- Python Copy File From one Directory to Another Example
- Python List All Dates Between Two Dates Example
- How to Add Months to Date in Python?