Assign variable in while loop condition in Python?
Try this one, works for files opened with open('filename')
for line in iter(data.readline, b''):
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)