0

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
1
  • The file_reader variable length might 0. Commented Dec 7, 2013 at 0:21

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.