Bogdan Janiszewski
Bogdan Janiszewski

Reputation: 2883

Unexpected results when converting while loop to for loop

I have a while loop that generally works well but I would like to convert it to a for loop. The while loop is as follows:

with open(filename) as a:
while tally != c:
    line = a.readline()
    c = line.strip()

Where I open a file, read each line until I find the line I am interested in. The for loop is as follows:

with open(filename) as a:
for line in enumerate (a):
    if tally == c:
        break
    elif tally != c:
        c = line

It appears that the loop just reads to the end of the file every time and turns the variable c into a tuple consisting of a random number and the last line of the file. I know the string contained in tally exists in the file because the while loop performs the intended function.

Upvotes: 0

Views: 32

Answers (2)

nitangle
nitangle

Reputation: 171

Instead of c=line it must be c=line.strip().

Upvotes: -1

user94559
user94559

Reputation: 60143

Fixed code:

with open(filename) as a:
    for line in a:
        if tally == c:
            break
        else:
            c = line.strip()

Two issues:

  1. for line in enumerate(a) means line gets a tuple on each iteration of the line number and the actual line from the file. Read up on enumerate to understand its use.
  2. c = line is different from c = line.strip() in your original loop.

Upvotes: 1

Related Questions