I'm trying to count the rows in a file until there's at least 5 rows, and then stop counting.
I can't figure out why this simple while loop seems to be generating an infinite loop:
row_count = 0
while row_count <= 5:
for row in file_reader:
row_count += 1
asked Dec 7, 2013 at 0:13
Jeff Widman
23.8k13 gold badges79 silver badges93 bronze badges
-
The file_reader variable length might 0.user1781498– user17814982013年12月07日 00:21:40 +00:00Commented Dec 7, 2013 at 0:21
1 Answer 1
The for loop will run to completion first before the while gets a chance to test row_count.
Break out of the for loop instead:
row_count = 0
for row in file_reader:
row_count += 1
if row_count > 5:
break
You can use enumerate() to generate the count:
for row_count, row in enumerate(file_reader):
if row_count > 5:
break
Last, but not least, there is itertools.islice():
from itertools import islice
for row in islice(file_reader, 5):
# only first five lines are iterated over
answered Dec 7, 2013 at 0:14
Martijn Pieters
1.1m326 gold badges4.2k silver badges3.4k bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py