new linereading standard?

Andrew Dalke dalke at acm.org
Mon Apr 24 22:20:04 EDT 2000


Pete Shinners wrote:
> it is a simple class
> that handles the "while 1: .... break" carnival for reading files.
[...]
> 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!)


Try looking at the standard 'fileinput' module.

> now i can code in a preferred style
>
> myfile = open('myfile.txt', 'r')
> for line in filelines(myfile):
>     print line
> myfile.close()

import fileinput
myfile = fileinput.FileInput('myfile.txt')
for line in myfile:
   print line
myfile.close()

Not quite the same, since it only deals with filenames and yours
uses any file-like object.

So the module for what you want is present.  You'll find that nearly
no one uses it.  Part of the reason is the standard idiom (your
'carnival') is used for a lot more than reading files, so people get
used to seeing it.  Another reason is the performance suffers some
since you have the extra method call overhead.

Indeed, I've only used fileinput in examples for non-Python people
where I don't want to have to explain the while 1:/test loop.  They
more easily follow "this is a black box thingy which returns input
lines" compared to having to explain "yes, I know it's a couple
extra lines compared to C, but you get used to it and it prevents
some hard to find errors."

                    Andrew
                    dalke at acm.org






More information about the Python-list mailing list