Assign variable in while loop condition in Python?
Starting Python 3.8
, and the introduction of assignment expressions (PEP 572) (:=
operator), it's now possible to capture the condition value (data.readline()
) of the while loop as a variable (line
) in order to re-use it within the body of the loop:
while line := data.readline():
do_smthg(line)
Try this one, works for files opened with open('filename')
for line in iter(data.readline, b''):
If you aren't doing anything fancier with data, like reading more lines later on, there's always:
for line in data:
... do stuff ...
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()
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.