我有f1.txt,这是一个文件,我希望用列表lst的连续元素替换所有出现的999。我有以下代码,但它不是很有效。
lst = ['1', '2', '3']
f1 = open('f1.txt', 'r')
f2 = open('f2.txt', 'w')
for no in lst:
for line in f1:
if 'some_text' in line:
f2.write(line.replace('999', no))
continue
else:
f2.write(line)
f1.close()
f2.close()
来自f1.txt的样本:
tags text something
some_text blablabla 999
other text whatever
some_text blablabla 999
non interesting text
some_text blablabla 999
结果应为:
tags text something
some_text blablabla 1
other text whatever
some_text blablabla 2
non interesting text
some_text blablabla 3
你能帮帮我吗?
谢谢
答案 0 :(得分:0)
lst = ['1', '2', '3']
f1 = open('f1.txt', 'r')
f2 = open('f2.txt', 'w')
idx = 0
for line in f1:
if ('some_text' in line) and ('999' in line):
f2.write(line.replace('999', lst[idx]))
idx += 1
else:
f2.write(line)
f1.close()
f2.close()