Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Read each line, replace string and save into a new file
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*

new_server new_server2 new_server3
*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'))

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

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

buran wrote Sep-15-2019, 01:13 PM:
Please, use proper tags when post code, traceback, output, etc. This time I have added tags for you.
See BBcode help for more info.
you want replace one word only?

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

with open(zabix_config) as zbx:
    zbx_config = # 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}')

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  update txt file but keep a specific line 3Pinter 1 87 Dec-09-2019, 05:48 PM
Last Post: Gribouillis
  python one line file processing har 4 230 Dec-09-2019, 06:10 AM
Last Post: har
  txt-file: read and append missing data sufi 1 126 Dec-07-2019, 08:12 AM
Last Post: Gribouillis
  Read csv file, parse data, and store in a dictionary markellefultz20 4 238 Nov-26-2019, 03:33 PM
Last Post: DeaD_EyE
  Save a file uploaded from client-side without having to read into memory andym118 3 162 Nov-21-2019, 07:34 AM
Last Post: DeaD_EyE
  line number of first and second occurance of string in a file mdalireza 1 89 Nov-18-2019, 09:55 AM
Last Post: perfringo
  Details of attachment files in a msg file such as file names save into a python list klllmmm 2 172 Nov-12-2019, 05:59 AM
Last Post: klllmmm
  Print string in a single line RavCOder 8 188 Nov-08-2019, 09:45 AM
Last Post: perfringo
  How to read text file line by line SriRajesh 1 108 Nov-05-2019, 01:51 PM
Last Post: snippsat
  Replace Line in Textfile Deadline 1 160 Nov-04-2019, 07:14 PM
Last Post: Larz60+

Forum Jump:

Users browsing this thread: 1 Guest(s)