Answer the code as it is written
As described, the file will remain open for the life of the program. As long as you refer to the res variable, it saves the generator life cycle, so the only way to get a with-statement to close the file is to continue calling next () until the for-loop completes normally.
How to clean the generator
A tool designed to clean the generator, generator.close () , which calls GeneratorExit inside the generator.
Here is some working code that shows how to do this:
def genfunc(filename): try: with open(filename) as datafile: for line in datafile: yield len(line) finally: print('Status: %s' % datafile.closed)
And here is an example session showing that the closing operation is actually happening:
>>> g = genfunc('somefile.txt') >>> next(g) 23 >>> g.close() Status: True
source share