Python - write txt file with a list

寵の児 提交于 2019-12-11 17:59:50

问题


I have a test.txt that contains:

-
anything1
go
-
anything2
go

And i wanna replace the '-' with my list and some query. Here is my code:

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

But my result is:

use 1
go
anything1 
go

use 1
go
anything2 
go

I need that the second 'use' be 'use 2' and not 'use 1'.

How I can fix this?

Thanks


回答1:


Try this instead:

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)


来源:https://stackoverflow.com/questions/47814761/python-write-txt-file-with-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!