Read each line, replace string and save into a new file - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Read each line, replace string and save into a new file (/thread-21121.html) |
Read each line, replace string and save into a new file - igormonteiro - Sep-15-2019 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* *Content of zabbix_agentd.conf*
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
RE: Read each line, replace string and save into a new file - Axel_Erfurt - Sep-15-2019 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() RE: Read each line, replace string and save into a new file - buran - Sep-15-2019 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) |