Chris's Wiki :: blog/python/ReadingRecordsThought Commentshttps://utcc.utoronto.ca/~cks/space/blog/python/ReadingRecordsThought?atomcommentsDWiki2007-12-17T16:22:12ZRecent comments in Chris's Wiki :: blog/python/ReadingRecordsThought.By Dan.Astoorian on /blog/python/ReadingRecordsThoughttag:CSpace:blog/python/ReadingRecordsThought:7a9105e929df0002dfeebc8bd129ab054aa82ca1Dan.Astoorian<div class="wikitext"><p>This is also an excellent application for generator functions. I think this alternative implementation does the same job a little more cleanly:</p>
<pre>
class RecordReader(object):
def __init__(self, fo, sre):
self.mre = re.compile(sre)
self.fo = fo
self.first = True
def readrecord(self):
rec = []
while True:
line = self.fo.readline()
if not line:
break
if self.mre.match(line) and not self.first:
yield rec
rec = [ line ]
else:
self.first = False
rec.append(line)
yield rec
</pre>
<p>The mainline then becomes:</p>
<pre>
for rec in reader.readrecord():
# process rec
</pre>
<p>--Dan</p>
</div>2007-12-17T16:22:12ZBy nothings on /blog/python/ReadingRecordsThoughttag:CSpace:blog/python/ReadingRecordsThought:7dac077168cf869e738a4dbd3196ee8a9bfc125cnothings<div class="wikitext"><p>Or you need to create a reader that allows you to 'unget' a line--which is much the same thing, but puts the smarts in the caller which maybe makes it more reuseable.</p>
</div>2007-12-17T13:32:49Z