Python Forum
Read each line, replace string and save into a new file
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

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}')
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs


Possibly Related Threads…
Thread Author Replies Views Last Post
  [SOLVED] Read text file from some point till EOF? Winfried 1 128 Oct-10-2021, 10:29 PM
Last Post: Winfried
  append a string to a modified line Mr_Blue 10 579 Sep-16-2021, 07:24 PM
Last Post: Mr_Blue
  Replace String in multiple text-files [SOLVED] AlphaInc 5 746 Aug-08-2021, 04:59 PM
Last Post: Axel_Erfurt
  Replace String with increasing numer [SOLVED] AlphaInc 13 882 Aug-07-2021, 08:16 AM
Last Post: perfringo
  Read csv file through PyCharm kimx0961 3 624 Aug-01-2021, 07:05 PM
Last Post: perfringo
  Why it does not print( Rejaul84 1 508 Jul-01-2021, 10:37 PM
Last Post: bowlofred
  How to capture string from a line to certain line jerald 1 453 Jun-30-2021, 05:13 PM
Last Post: Larz60+
  Read and write active Excel file euras 4 633 Jun-29-2021, 11:16 PM
Last Post: Pedroski55
  [Solved] Reading every nth line into a column from txt file Laplace12 7 954 Jun-29-2021, 09:17 AM
Last Post: Laplace12
  [Solved] Trying to read specific lines from a file Laplace12 7 950 Jun-21-2021, 11:15 AM
Last Post: Laplace12

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020