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
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.