简体   繁体   中英

python file.write adding multiple lines in for loop

In the following code the output adds each line 2 times

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()

If i comment out one of the config_out.write it is fine; but I want 2 in place replacements in the file .

You need to do the line.replace() twice, and the config_out.write() once:

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM