new linereading standard?

Pete Shinners pete at visionart.com
Mon Apr 24 19:00:44 EDT 2000


i've come to the point where i can't get by even the simplest python
project without dumping this code into my files. it is a simple class
that handles the "while 1: .... break" carnival for reading files.

i've seen a couple arguments back and forth of the cleanliness of this
syntax, and i never payed strong attention, but i must admit i find it
both ugly and ackward.

i'm sure someone has posted a class like the before, but i'm hoping it
can one day make it in as a python standard someday. (6.0, there's still
time!)

class filelines():
    def __init__(self, file):
        self.file = file
    def __getitem__(self, index):
        line = self.file.readline()
        if not line: raise IndexError
        return line

now i can code in a preferred style

myfile = open('myfile.txt', 'r')
for line in filelines(myfile):
    print line
myfile.close()

as opposed to

myfile = open('myfile.txt', 'r')
while 1:
    line = myfile.readline()
    if not line: break
    print line
myfile.close()

as a person trying to introduce his friends to python, i repeatedly find
this is the ugliest wart while doing basic stuff with python.

anyways, i now use this code ALWAYS. unfortunately, i haven't found a
good way to make this part of my standard environment while working on
many different machines.

if someone wants, i'm close to creating a much improved version of this
class that can optionally handle trickier situations (like continuing
lines ending with \). perhaps also allowing input of a filename string
and perform the needed open and close requests as well.

anyways, what are peoples thoughts if someone was to create a more
robust class like this, would or could it ever be grafted into a later
python release?

(i'm also anxious for some += style operators, and a := operator that
performs assignment and returns the assigned value (as mentioned in the
FAQ))

another simple option would be to have the filehandle objects evaluate
to boolean 0,FALSE when you cannot read from the file

--
_____Pete Shinners______
   pete at visionart.com






More information about the Python-list mailing list