[英]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
我需要第二個“用途”是“用途2”,而不是“用途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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.