Python - 用列表写入txt文件

时间:2017-12-14 13:40:31

标签: python file-handling

我有一个包含以下内容的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

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

我如何解决这个问题?

由于

1 个答案:

答案 0 :(得分: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)