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