faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

1 of 2 people (50%) answered Yes
Recently 0 of 1 people (0%) answered Yes

Entry

YAS to the "Reading line-by-line" problem

Jul 5th, 2000 10:01
Nathan Wallace, Hans Nowak, Snippet 187, Moshe Zadka


"""
Packages: files
"""
FILENAME = "c:/autoexec.bat"
# change this to a valid file n your system; it won't be changed or
# overwritten
"""
(YAS == Yet Another Solution)
This solution introduces file-like objects which do the Right Thing(TM) at
EOF: raise EOFError (instead of returning an empty string)
"""
#----------------- cut here ------------------
class File:
        '''\
        File-like objects which throw EOFError on End-of-File.
        Initialize with a file-like object.
        '''
        def __init__(self, file):
                self.__file=file
        def __getattr__(self, name):
                if name[:4]!='read':
                        return getattr(self.__file, name)
                return _Wrap(getattr(self.__file, name))
class _Wrap:
        def __init__(self, function):
                self.function=function
        def __call__(self, *args, **kw):
                ret=apply(self.function, args, kw)
                if ret=='': raise EOFError, 'no more data in file'
                return ret
def open(file, mode='r'):
        '''\
        return a file like object open to /file/ with mode /mode/,
        which throws an EOFError on EOF
        '''
        import __builtin__
        return File(__builtin__.open(file, mode))
def _test():
        import sys
        file=open(FILENAME) # changed by PSST
        try:
                while 1:
                        sys.stdout.write(file.readline())
        except EOFError: pass
if __name__=='__main__':
        _test()