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.
In order to get started just create an
app.py file and copy paste the following code
# 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.
So here you can see the original
file.txt which is shown below.
Here we are replacing the word
woman inside the application and now after executing this python script this text file will become like this as shown below