[英]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.