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
- Get Last 2 Digits of Number in Python Tutorial Example
- How to Sum of First and Last Digit of Number in Python?
- How to Get First and Last Digit of Number in Python?
- Get the Last Digit of Number in Python Tutorial Example
- Get the First Digit of Number in Python Tutorial Example
- How to Remove All Decimals from Number in Python?
- How to Convert String to Float with 2 Decimal Places in Python?
- How to Format Number to 2 Decimal Places in Python?