[Python-Dev] RE: fileinput.py
Ka-Ping Yee
ping@lfw.org
Fri, 5 Jan 2001 16:01:53 -0600 (CST)
On Fri, 5 Jan 2001, Thomas Wouters wrote:
> On Fri, Jan 05, 2001 at 03:46:10PM -0500, Tim Peters wrote:
> > That is, "<>" is usually used simply as an abbrevision for <STDIN>, and I
> > bet *most* Perl programmers don't even know "<>" is more general than that.
>
> Well, I can't say anything about *most* Perl programmers, but all Perl
> programmers I know (including me) know damned well what <> does, and use it
> frequently. And in all the ways: no arguments meaning <STDIN>, a list of
> files meaning open those files one at a time, using - to include stdin in
> that list, accessing the filename and linenumber, etc.
I was just about to chime in and say the same thing. I don't even
program in Perl any more, and i still remember all the ways that <> works.
For text-processing scripts, it's unbeatable. It does pretty much
exactly everything you want, and the idiom
while (<>) {
...
}
is simple, quickly learned, frequently used, and instantly recognizable.
import sys
if len(sys.argv) > 1:
file = open(sys.argv[1])
else:
file = sys.stdin
while 1:
line = file.readline()
if not line:
break
...
is much more complex, harder to explain, harder to learn, and runs slower.
I have two separate suggestions:
1. Include 'sys' in builtins. It's silly to have to 'import sys'
just to be able to see sys.argv and sys.stdin.
2. Put fileinput.input() in sys.
With both, the while (<>) idiom becomes:
for line in sys.input():
...
-- ?!ng
"This code is better than any code that doesn't work has any right to be."
-- Roger Gregory, on Xanadu