Reputation: 2883
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
Reputation: 60143
Fixed code:
with open(filename) as a:
for line in a:
if tally == c:
break
else:
c = line.strip()
Two issues:
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.c = line
is different from c = line.strip()
in your original loop.Upvotes: 1