user2493988 user2493988 - 1 month ago 6
Python Question

How do I replace items in a file with items in a list

I have f1.txt, a file in which I want to replace all occurrences of 999 with the consecutive elements of the list lst. I have the following code, but it doesn't quite work.

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


Sample from f1.txt:

tags text something
some_text blablabla 999
other text whatever
some_text blablabla 999
non interesting text
some_text blablabla 999


The result should be:

tags text something
some_text blablabla 1
other text whatever
some_text blablabla 2
non interesting text
some_text blablabla 3


Can you please help me?

Thank you

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