Two problems with Python's file iteratorsModern versions of Python let you process each line in a file in a
simple way, with just '
If you run this without standard input redirected, you will immediately notice the problems:
Both problems are caused by the same underlying decision: despite using
Unix's traditional stdio functions, which do their own buffering, Python
adds its own layer of forced buffering for file iteration. This forced
buffering even has the perverse effect that you can't mix file iteration
and explicit (Since this is a deliberate and long standing design decision, I suspect that the Python people are not interested in bug reports.) These bugs might seem relatively minor, except that reading from terminals isn't the only case where you really need to handle input a line at a time, without insisting on buffering up a bunch of it; another is dealing with line oriented network protocols. As a result of running into these issues I reflexively avoid file
iteration in my own code, which makes me grumpy when I write yet another
'read the lines' loop. (By now, I have the necessary Sidebar: coding around the problemThe necessary
Note that even if you want the newline stripped off the end of the line,
you do not want to strip it before you do the ' (Speaking from personal experience, this is an embarrassing mistake to make, although you usually catch it fast.) It's also possible to fix things up with an 'iterfile' routine, like this:
Then instead of ' (4 comments.)
|
These are my WanderingThoughts GettingAround This is part of CSpace, and is written by ChrisSiebenmann. * * * Atom feeds are available; see the bottom of most pages. Categories: links, linux, programming, python, snark, solaris, spam, sysadmin, tech, unix, web |