Much simplified version exactly as suggested Zoran Isailovski - no class needed either. Works as a very tutorial for list comprehensions :)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
def process_lines(fd, handler, cond=None): """ Process all lines in fd if cond is not None, process only lines returning True for cond """ if cond is not None: [ handler(line) for line in fd.readlines() if cond(line) ] else: [ handler(line) for line in fd.readlines() ] if __name__ == '__main__': import sys fname = sys.argv def line_printer(line): sys.stdout.write(line) # print all lines containing 'if' process_lines(file(fname), line_printer, lambda n: n.find('file') > -1) lst =  # read all lines to list process_lines(file(fname), lst.append) for line in lst: sys.stdout.write(line)
Old LineReader class was thrown to /dev/null - fd will really be exhausted during each call of process(), so a simple method is enough. As Zoran Isailovski suggested, a plain list comprehension is enough. So process_method() is useful only for newbies not yet getting the hang of list comprehensions, but they should definitely look for them - they are concise, easy to learn and yet powerful.