You have:
def file_gen(f_name): f = open(f_name) line = f.readline() yield line
Note line = f.readline() This is only 1 line from the file.
For comparison:
def g(x): li=range(x) yield li.pop() print list(g(10))
with this:
def g(x): li=range(x) while li: yield li.pop() print list(g(10))
yield can only be called once with a specific object or expression. When used by the receiver, it must be regenerated. So you need a loop around reading each line of the file.
You can use your second (less readable) form as follows:
def file_gen(f_name): f = open(f_name) while True: line = f.readline() if not line: break yield line
To create return items you need a loop. In your first case, for line in f: yield line is a loop.
I would rewrite your function as follows:
def file_gen(f_name): with open(f_name) as f: for line in f: yield line
source share