I just came across this piece of code
while 1:
line = data.readline()
if not line:
break
#...
and thought, there must
You could do:
line = 1
while line:
line = data.readline()
According to the FAQ from Python's documentation, iterating over the input with for
construct or running an infinite while True
loop and using break
statement to terminate it, are preferred and idiomatic ways of iteration.
Like,
for line in data:
# ...
? It large depends on the semantics of the data
object's readline semantics. If data
is a file
object, that'll work.
As of python 3.8 (which implements PEP-572) this code is now valid:
while line := data.readline():
# do something with line
This isn't much better, but this is the way I usually do it. Python doesn't return the value upon variable assignment like other languages (e.g., Java).
line = data.readline()
while line:
# ... do stuff ...
line = data.readline()
Try this one, works for files opened with open('filename')
for line in iter(data.readline, b''):