Python - 用列表写入 txt 文件

Python - write txt file with a list

我有一个 test.txt 包含:

-
anything1
go
-
anything2
go

我想用我的列表和一些查询替换“-”。这是我的代码:

x = ['1', '2']
i=0
with open("test.txt", "r") as fin:
    with open("result.txt", "w") as fout:
        for line in fin:
            fout.write(line.replace('-','\nuse '+(str(x[i]))+'\ngo\n'))
            i+=i

但我的结果是:

use 1
go
anything1 
go

use 1
go
anything2 
go

我需要第二个 'use' 是 'use 2' 而不是 'use 1'。

我该如何解决这个问题?

谢谢

试试这个:

i = (x for x in ['1', '2'])

with open("test.txt") as fin, open("result.txt", "w") as fout:
    for line in fin:
        if line.startswith('-'):
            fout.write(line.replace('-', '\nuse {}\ngo\n'.format(next(i))))
        else:
            fout.write(line)