There are a variety of ways you could do this; I think this is the most straightforward:
def search_file(filename, searchword):
my_file = open(filename)
output_file = open('fieldsModified.txt', 'w+')
for i, line in enumerate(my_file):
if searchword in line:
print( str(i) + ' - ' + line )
output_file.write( str(i) + ' - ' + line )
my_file.close()
output_file.close()
Whether this is suitable for your needs depends on how large are the files you need to search, whether you care about uppercase vs lowercase etc. I’m not sure whether this directly addresses the problem you are having, so if I’m missing what you were trying to ask please say so…
1
solved Getting the line in which occurrence of words in files appear? [closed]