我正试图最终创建一个函数,该函数从文件中提取折扣代码,将其发送给用户,然后从文件后记中删除它们。我正在尝试使用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))
答案 0 :(得分:1)
检查应该在循环中。尝试这个。
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)
...