0

This nested loop works fine when reading lists:

list = [1,2,3,4,5]
num = 0
while num < 5:
  for i in list:
     print(i)
     num += 1

This loop will print all elements in the list. The problem is that it doesn't work at all when reading textfiles. Instead of printing the first 5 lines of text it will read through all and print them.

f = open(r'C:\Users\Me\Python\bible.txt')
num = 0
while num < 50:
   for line in f:
      print(line)
      num += 1

I can only assume that the num variable doesn't increase after each iteration, is there a reason for this, and is there a solution?

3
  • have you tried stepping through it a line at a time and seeing what the values the variables take? Commented Feb 8, 2013 at 16:26
  • Also note that looping over a file as an iterator, uses a read-ahead buffer that reads 2k blocks at a time, for performance. So it could be that that reads all of the file if it is small enough. Commented Feb 8, 2013 at 16:28
  • 1
    Your first loop loops over all the values in list too. Try that again with a larger list or with num < 3 and see what happens.. Commented Feb 8, 2013 at 16:30

2 Answers 2

2

the code

for line in f:
    print line
    num += 1

is looping over all the lines in your file. At the same time it increase num by one. So at the end of the for-loop num will be equal to the number of lines in the files, probably larger than 50, so it will exit from the while-loop.

Using your style you should write:

for line in f:
   print line
   num += 1
   if num > 50: break

Also the first code has the same problem. Why do you need two loops if you want to loop over one structure in one dimension? Your codes are not very pythonic, for example you should rewrite them as:

list = [1,2,3,4,5]
for i in list:
   print i

for i,line in enumerate(f):
    print line
    if i > 50: break
Sign up to request clarification or add additional context in comments.

Comments

1

I would not believe your code works, even in the first example. Since you code two nested loops, the inner loop wil always complete, before the termination of the outer loop is checked. I would suggest to drop the outer looper and insert something like

if num > 50: break

into the inner loop.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.