How to overide "for line in file:"

David David
Sun Feb 22 10:51:01 EST 2004


On Sun, 22 Feb 2004 10:07:22 +0100, Peter Otten <__peter__ at web.de>
wrote:

># change the original iterator's behaviour
>class myFile2(file):
>    def __init__(self, name, affine):
>        self.affine = affine
>        file.__init__(self, name)
>
>    def next(self):
>        line = file.next(self)
>        r, c = line[:-1].split(",")
>        return self.affine(r,c)
>
>#create sample data
>r = iter(range(10))
>sample = "".join(["%d,%d\n" % (i,j) for (i,j) in zip(r,r)])
>file("tmp.txt", "w").write(sample)
>
>def op(a, b):
>    return int(a)*int(b)
>
>
>for v in myFile2("tmp.txt", op):
>    print v,
>print
>

Thank you, all!

Shalabh points out the failure of my understanding ["...note that the
example from Terry Reedy does not have a 'list of lines' - lines is an
iterable, which means it could be a file object.], and your second
example [class myfile2] is exactly what I had been trying to do.

dave




More information about the Python-list mailing list