My try at this problem: # filecounter.py: #!/usr/bin/env python
class CountedFile(file): def __init__(self, *args, **kw): self.linecount = 0 super(CountedFile, self).__init__(*args, **kw) def read(self, *args): data = super(CountedFile, self).read(*args) self.linecount += data.count("\n") return data def readline(self, *args): data = super(CountedFile, self).readline(*args) self.linecount += data.count("\n") return data def next(self): data = super(CountedFile, self).next() self.linecount += data.count("\n") return data if __name__ == "__main__": f = CountedFile("filecounter.py") f.readline() print f.linecount for x in f: print "%3d: %s" % (f.linecount, x.rstrip()) Only drawback: It cannot be used for already open files, like sys.stdin. For these a delegation based solution (which probably could be coded up with __getattr__) seems plausible. One explanation: One needs to reimplement all reading interfaces, because readline doesn't use an overridden read method. Andreas Am Dienstag, den 16.08.2005, 15:35 +0200 schrieb Duncan Gibson: > I wrote: > > > class MyFile(file): > > > etc > > > > > > I couldn't see how to have an instance of MyFile returned from the > > > built-in 'open' function. I thought this was the crux of the problem. > > Kent Johnson replied: > > open() is actually just an alias for file(): > > >>> open is file > > True > > Thank you very much! You have just provided me with the vital piece of > information I needed and everything has just clicked into place. > > Now that I know that I've searched the documentation again and found: > > The file() constructor is new in Python 2.2 and is an alias for > open(). Both spellings are equivalent. The intent is for open() > to continue to be preferred for use as a factory function which > returns a new file object. The spelling, file is more suited to > type testing (for example, writing "isinstance(f, file)"). > > See http://docs.python.org/lib/built-in-funcs.html#l2h-25 > > Cheers > Duncan > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor
signature.asc
Description: Dies ist ein digital signierter Nachrichtenteil
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor