简体   繁体   中英

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))

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)
         ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM