jkorn95
jkorn95

Reputation: 85

python while loop not stopping after condition is met?

I'm trying to eventually create a function that pulls discount codes from a file, sends them to a user, and then deletes them from the file afterword. I'm trying to use a while loop to accomplish this, but it's not stopping when the condition is met. Instead, it's reading to the end of the file every time, and the len(count) value is always equal to the number of lines in the file. Can anyone tell me what I'm missing here?

count = []
with open('codes.txt', 'w') as f:
    while len(count) < 10:
        #print(len(count))
        for line in lines:
            if '10OFF' in line:
                count.append(line)
                line = line.replace(line, "USED\n")
                #f.write('USED\n')
                #line = line + ' USED'

                f.write(line)
                print(line)
            #elif '10OFF' not in line:
                #print('not in line')
    else:
        print('all done')
        print(len(count))

Upvotes: 0

Views: 685

Answers (1)

Samuel Chen
Samuel Chen

Reputation: 2273

Check should in loop. try this.

count = []
with open('codes.txt', 'w') as f:
    #print(len(count))
    for line in f.readlines():
        if '10OFF' in line:
            count.append(line)
            line = line.replace(line, "USED\n")
            #f.write('USED\n')
            #line = line + ' USED'

            f.write(line)
            print(line)
        if len(count) >= 10:
            break

print('all done')
print(len(count))

Answer to comment - your lines were deleted after 10. Open another file for output.

with open('codes.txt', 'r') as f:
    with open('codes_output.txt', 'w') as fo:
         ...
         fo.write(line)
         ...

Upvotes: 1

Related Questions