new linereading standard?
Johann Hibschman
johann at physics.berkeley.edu
Tue Apr 25 14:23:23 EDT 2000
Robin Becker writes:
> am I wrong for writing
> for line in open('myfile.txt').readlines():
> print line
Of course not! Wrongness is such a relative thing that no one,
especially inhuman compilers, clearly cannot judge it. If it seems
right to you, that is all that matters.
<wink>
But seriously, I don't think there's anything wrong with that.
It depends on what you're doing. You can get away with a lot of
syntax crunching if what you're doing is basically simple. That
code fits the basically simple criteria in my brain.
In short, looks fine to me, and I do it a lot, when all I need from a
file is a list of lines in order.
ObComplexity:
To go off on a wild tangent, this reminds me of the whole map/lambda
functional programming fracas. See, I agree with most people that I
don't really want to see code like
map(lambda s: string.split(string.strip(s), ',')[0],
open('data.dat').readlines())
I much prefer
out = []
for s in open('data.dat').readlines():
fields = string.split(string.strip(s), ',')
out.append(fields[0])
But, if I'm doing this at the interactive prompt, what I end up typing
is most often something like:
>>> lines = open('data.dat').readlines()
>>> lines = map(string.strip, lines)
>>> lines = map(lambda l: string.split(l, ','), lines)
>>> out = map(lambda fs: fs[0], lines)
So, basically, I find the functional stuff much more useful from
the command line than I do from actual programs. I think of the
right transform, then I apply it. Interesting.
Heh. I'm free-associating here, please bear with me. Anyone else have
this experience?
--Johann
--
Johann Hibschman johann at physics.berkeley.edu
More information about the Python-list
mailing list