while c = f.read(1)
Greg McIntyre
greg at puyo.cjb.net
Fri Aug 19 01:21:53 EDT 2005
I have a Python snippet:
f = open("blah.txt", "r")
while True:
c = f.read(1)
if c == '': break # EOF
# ... work on c
Is some way to make this code more compact and simple? It's a bit
spaghetti.
This is what I would ideally like:
f = open("blah.txt", "r")
while c = f.read(1):
# ... work on c
But I get a syntax error.
while c = f.read(1):
^
SyntaxError: invalid syntax
And read() doesn't work that way anyway because it returns '' on EOF
and '' != False. If I try:
f = open("blah.txt", "r")
while (c = f.read(1)) != '':
# ... work on c
I get a syntax error also. :(
Is this related to Python's expression vs. statement syntactic
separation? How can I be write this code more nicely?
Thanks
More information about the Python-list
mailing list