簡體   English   中英

滿足條件后,python while循環不會停止嗎?

[英]python while loop not stopping after condition is met?

我試圖最終創建一個函數,該函數從文件中提取折扣代碼,將其發送給用戶,然后從文件后記中刪除它們。 我正在嘗試使用while循環來完成此操作,但是在滿足條件時它不會停止。 相反,它每次都讀取到文件末尾,並且len(count)值始終等於文件中的行數。 誰能告訴我我在這里想念的東西嗎?

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

檢查應該循環。 嘗試這個。

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

發表評論的答案-您的行在10后被刪除。打開另一個文件進行輸出。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM