python file.write在for循环中添加多行

时间:2014-09-13 06:33:17

标签: python

在以下代码中,输出每行添加2次

template_file = open("../conf/"+config_template_code+".tmpl",'r')
        config_out = open("../sites-enabled/"+domain_name+".conf",'w')
        for line in template_file:
                config_out.write(line.replace('CPANELIP',cpanel_ipv4))
                config_out.flush()
                config_out.write(line.replace('DOMAINNAME',domain_list))
                config_out.flush()
        template_file.close()
        config_out.close()

如果我注释掉其中一个config_out.write就可以了;但我想在文件中替换2个。

1 个答案:

答案 0 :(得分:3)

您需要执行line.replace()两次,config_out.write()一次:

                line = line.replace('CPANELIP',cpanel_ipv4)
                line = line.replace('DOMAINNAME',domain_list)
                config_out.write(line)
                config_out.flush()