Python 3 Script to Find and Replace Text or String in All Occurences in a Text File Full Tutorial For Beginners

Python 3 Script to Find and Replace Text or String in All Occurences in a Text File Full Tutorial For Beginners

 

 

Welcome folks today in this blog post we will be writing a python script which will be finding and replacing text in all occurences in the text file. All the full source code of the application is given below.

 

 

 

Get Started

 

 

In order to get started just create an app.py file and copy paste the following code

 

app.py

 

 

# Read in the file
with open('file.txt', 'r') as file :
  filedata = file.read()

# Replace the target string
filedata = filedata.replace('man', 'woman')

# Write the file out again
with open('file.txt', 'w') as file:
  file.write(filedata)

 

 

Here we are using the built in open function inside python to open the text file and then we are providing the input term that needs to be replaced with the target string. And then after replacing in all occurences it will again create the file again.

READ  Python 3 Tkinter Button Tutorial to Bind OnClick Event and Runs Command Automatically in GUI Desktop App Full Project For Beginners

 

So here you can see the original file.txt which is shown below.

 

 

 

 

Here we are replacing the word man with woman inside the application and now after executing this python script this text file will become like this as shown below

 

 

 

Leave a Reply