[BangPypers] [Novice] Question on File seek and tell methods
Navin Kabra
navin at smriti.com
Tue Jun 18 07:34:09 CEST 2013
> The way I would do this is as follows:
I would use itertools to make the code more concise. Also, a strong
recommendation that `with` should be used whenever you want to open a
file. And use of the `print_function` from `__future__` for python-3
compatibility.
from __future__ import print_function
from itertools import dropwhile
with open('/tmp/foo.txt') as f:
for line in dropwhile(lambda l: not l.startswith('Chennai'), f):
# process line here
print(line.strip())
if line.startswith('Angry Birds'):
break
Note: there is also `takewhile` in itertools that could have been
useful if the 'Angry Birds' line is not to be included in the selected
lines.
More information about the BangPypers
mailing list