Using python 3, Can anyone tell me how to search and replace text in a file?
Look at my code:
import os
import sys
import fileinput
print ("Text to search for:")
textToSearch = input( "> " )
print ("Text to replace it with:")
textToReplace = input( "> " )
print ("File to perform Search-Replace on:")
fileToSearch = input( "> " )
#fileToSearch = 'D:\dummy1.txt'
tempFile = open( fileToSearch, 'r+' )
for line in fileinput.input( fileToSearch ):
if textToSearch in line :
print('Match Found')
else:
print('Match Not Found!!')
tempFile.write( line.replace( textToSearch, textToReplace ) )
tempFile.close()
input( '\n\n Press Enter to exit...' )
Input file:
hi this is abcd hi this is abcd
This is dummy text file.
This is how search and replace works abcd
At the point when I search and replace the word 'ram' with 'abcd' in above information document, it functions as an appeal. Yet, when I do it the other way around for example replacing 'abcd' by 'ram', some garbage characters are left toward the end.
Replacing 'abcd' with 'ram'
hi this is ram hi this is ram
This is dummy text file.
This is how search and replace works rambcd