Friday, December 22, 2017

Generator Functions - Yield Python

So Yield is a keyword.first let's take an example.

student = []

def read_file():
        try:
              f=open("students.txt","r")
               for student in read_students(f):
                      students.append(student)
               f.close()
         except Exception:
                print("Could not read file")

def read_students(f):
       for line in f:
              yield line

read_file()
print(students)

So what I have done is created a single function read_students and what it does
it iterated over the file and yield the single line from that file.

No comments: