From this context:
import itertools
lines = itertools.cycle(open('filename'))
I’m wondering how I can implement that same ‘feature’ but rereading the file when it reaches the end, so if the file got changed since first iteration it’s reloaded before starts another cycle. (hope I’ve explained well)
Thank you in advance! 🙂
I’d use:
or:
You can also write a generator comprehension (I think I like this best!):
Here’s the imperative (statement-based) equivalent:
Or, with Python 3.3 (using PEP 380 subgenerator delegation):
One problem with all of these is that (on a GC platform e.g. Jython) the file will not be closed until the file object is GCed, which could happen some time later. To prevent the open file leaking, you have to call
closeon it or use a contextmanager (withstatement). This comes out naturally in the imperative form:or
Trying to close the file with a generator comprehension becomes highly contrived:
It’d be nice if Python had a way to specify that an
opened file should close itself upon reaching the end of the file, or a way to tell a contextmanager-iterator to close itself onStopIteration.