old = open('./old.txt')
new = open('./new.txt','w')
for line in file:
if '22%' in line:
new.write(line)
new.close()
上面的代码将包含22%的行写入新文件。应该进行哪些更改以编写紧跟在包含22%的行之后的行?
例如: old.txt有
abc def g22%hi jkl mno
new.txt应该有
g22%hi jkl
答案 0 :(得分:2)
您可以使用标记或使用其他人在评论中说的next
:
some_flag = False
for line in file:
if some_flag:
new.write(line)
some_flag = False
if '22%' in line:
new.write(line)
some_flag = True
new.close()
答案 1 :(得分:0)
您可以对现有代码进行最简单的更改,并解决问题:
old = open('./old.txt')
new = open('./new.txt','w')
prevLine = ""
for line in file:
if '22%' in line or '22%' in prevLine:
prevLine = line
new.write(line)
new.close()