Python Forum

Full Version: Read each line, replace string and save into a new file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to replace a string based on each line of list.txt and create a new file with the name of the string collected.

*Content of list.txt*

Output:
new_server new_server2 new_server3
*Content of zabbix_agentd.conf*
Output:
Hostname=server
fin = open("zabbix_agentd.conf", "rt")
fout = open(new_server_string_collected, "wt")

for line in fin:#
	fout.write(line.replace('Hostname=server', 'Hostname=new_server'))
	
fin.close()
fout.close()

fh = open('list.txt')
while True:
    line = fh.readline()
    print(line)
    if not line:
        break
fh.close()
*Results expected*

1. python sample.py
2. file created: new_server
3. cat new_server

Output:
Hostname=new_server
you want replace one word only?

fin = open("zabbix_agentd.conf", "r")
fout = open(new_server_string_collected, "w")
 
str_in = fin.read()
fin.close()
str_out = str_in.replace('Hostname=server', 'Hostname=new_server')
fout.write(str_out)
fout.close()
something within these lines
zabix_config = 'zabbix_agentd.conf'
server_list = 'list.txt'

with open(zabix_config) as zbx:
    zbx_config = zbx.read() # read full config file content

with open(server_list) as f:
    for line in f:
        line =  line.strip() # remove the new line ending
        with open(f'{line}') as out_f:
            new_zbx = zbx_config.replace('Hostname=server', f'Hostname={line}')
            out_f.write(new_zbx)