Iterating over a binary file
Ville Vainio
ville.vainio at spamster_tut_remove.fi
Tue Jan 6 16:52:30 EST 2004
Paul Rubin <http://phr.cx@NOSPAM.invalid> writes:
> > The above code works, but I don't like making two read() calls. Any
> > way to avoid it, or a more elegant syntax? Thanks.
>
> You can make it even uglier:
>
> f = file(filename, 'rb')
> while 1:
> data = f.read(1024)
> if len(data) <= 0:
> break
> someobj.update(data)
> f.close()
>
> There's been proposals around to add an assignment-expression operator
> like in C, so you could say something like
>
> f = file(filename, 'rb')
> while len(data := f.read(1024)) > 0:
> someobj.update(data)
> f.close()
It's funny, but I find the first version much more readable than the
second one. Especially if I consciously forget the "do lots of stuff
in condition part of while" indoctrination from C. If there is lots of
stuff in while you have to stare at it a bit more, and it becomes
"idiomatic", something you learn, perhaps even cookbook stuff, instead
of obvious-as-such.
> but that's the subject of holy war around here too many times ;-). Don't
> hold your breath waiting for it.
Probably true. Instead of ":=", I wouldn't mind getting rid of
expressions/statements difference as a whole.
--
Ville Vainio http://www.students.tut.fi/~vainio24
More information about the Python-list
mailing list