Есть несколько способов использовать генератор - unsing next()
использует только его (следующее) значение.
Создать файл:
def gen_file():
with open("contacts.csv","w") as f:
f.write("""Name01, 89888
Name02, 8885445
Name03, 54555
Name04, 55544584
Name05, 55855
Python, 100
BigPi, 444
Python, 101
""")
Использовать его:
gen_file()
def search(keyword, filename="contacts.csv"):
"""Changed to use .. with open() as f: ... style syntax."""
with open(filename, 'r') as f:
for line in f:
if keyword in line:
yield line
# consume all of it into a list - you can reuse it
print("-"*40)
the_generator = search('Python', 'contacts.csv')
contacts = list(the_generator)
print(*contacts, sep="")
print("-"*40)
# decompose the generator directly for printing
the_generator = search('Python', 'contacts.csv')
print(*the_generator, sep="" )
print("-"*40)
# use a for loop over the generated results
the_generator = search('Python', 'contacts.csv')
for li in the_generator:
print(li, end="") # remove end=\n
print("-"*40)
# using str.join to create the output
the_generator = search('Python', 'contacts.csv')
print("".join(the_generator))
print("-"*40)
# loop endlessly until StopIteration is raised
try:
while True:
print(next(the_generator), end="")
except StopIteration:
pass
и т. Д.
Вывод (несколько раз):
----------------------------------------
Python, 100
Python, 101
«Лучшим», если вы не используете сгенерированные значения, является, вероятно, print(*the_generator,sep="")
или более явное:
# use a for loop over the generated results
the_generator = search('Python', 'contacts.csv')
for li in the_generator:
print(li,end="") # remove end=\n
Вы также можете прочитать здесь: Использование yield from с условным в python