Write a python program to search a word in a file and replace with another word

APJ ABDUL KALAM TECHNOLOGICAL UNIVERSITY
FIFTH SEMESTER M.C.A. DEGREE EXAMINATION, DECEMBER 2018
Course Code: RLMCA369
Course Name: PYTHON PROGRAMMING

import re<br>#input file<br>fin = open("/content/sample.txt", "rt")<br>#output file to write the result to<br>fout = open("/content/out.txt", "wt")<br>fput = open("/content/put.txt", "wt")<br>#for each line in the input file<br>for line in fin:<br>   #read replace the string and write to output file<br>  fout.write(line.replace('input', 'output'))<br>  fput.write(re.sub(r'file', 'files', line))<br>#close input and output files<br>fin.close()<br>fput.close()<br>fout.close()

Here we represented two type to replace one using string replace method and other using regular expression sub

first we read the file using open function then used for loop to iterate each line using line var , then at each line the line is replaced with the replacements

Leave a reply