Python-使用清单写入txt档案 [英] Python - write txt file with a list

查看:232
本文介绍了Python-使用清单写入txt档案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个test.txt,其中包含:

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

但是我的结果是:

use 1
go
anything1 
go

use 1
go
anything2 
go

我需要第二个用途"是用途2",而不是用途1".

I need that the second 'use' be 'use 2' and not 'use 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)

这篇关于Python-使用清单写入txt档案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆