I have made a generator function which search a csv file using a keyword and I want to print the results if there is something. How can I do that without using the print(next(gen_results)) over and over again?
I have tried a try-catch statement for the stopIteration, when there is no matching of keyword with a contact but I want a more concise solution.
def search(keyword, filename):
f = open(filename, 'r')
for line in f:
if keyword in line:
yield line
f.close()
the_generator = search('Python', 'contacts.csv')
print(next(the_generator))
print(next(the_generator))
contacts.csv
Name01, 89888
Name02, 8885445
Name03, 54555
Name04, 55544584
Name05, 55855
Python, 100
BigPi, 444
Python, 101
I expect the output to be a statement as 'Nothing Found',if there are no contacts with the keyword. In case there are contacts with the keyword, it outputs all the listings.