问题
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