Why is "while" ticking me off???

Alex the_brain at mit.edu
Thu Oct 5 20:59:42 EDT 2000


> I have a file that I want to read line-by-line, and stop reading when I run
> out of lines.  My first desire was to attempt:
> 
> while line = fp.readline():
>     do something with 'line'

I know what you mean.  It's really a superficial problem, but it
grates.  One thing you can do  is wrap the file object in a class, like

class Whileable_File:

    def __init__(self, file_object):
        self.file = file_object

    def readline(self, size=None):
        if size is None:
            self.line = self.file.readline()
        else:
            self.line = self.file.readline(size)
        return self.line

Another is to check out the fileinput class.

Alex.

-- 
Speak softly but carry a big carrot.




More information about the Python-list mailing list