[英]Python - write txt file with a list
I have a test.txt that contains: 我有一个test.txt,其中包含:
-
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'. 我需要第二个“用途”是“用途2”,而不是“用途1”。
How I can fix this? 我该如何解决?
Thanks 谢谢
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.