How to change a specific word in one TXT by another

-2

I need to change the configuration of the Zabbix server that is in this directory C:\zabbix\conf\zabbix_agentd.win.conf

I need to replace the word: hostname= with hostname=192.168.1.1

I did this, but the part under hostname did not understand where to put the name to look for and where to put the word that will replace. I'm using Python 3.6

import socket
import re

hostname = socket.gethostname()

with open('C:\zabbix\conf\zabbix_agentd.win.conf') as f:
    for l in f:
        s = l.split('*')
        editar = re.sub(r"\b%s\b" % s[0] , s[1], editor)
    
asked by anonymous 27.06.2018 / 16:21

1 answer

1

Your code does not make much sense for what you're asking for. You do not need to use regular expressions in your case, nor split . Just replace , which is the most basic method that does this and is a function of class str .

In addition, changing the variables after reading the file in read mode does not change the file. To change the file, it is necessary to open it in writing mode (passing 'w' as second argument of open ) and write its data with write or writelines .

Suppose my hostname is 'DESKTOP-PI3R74I' and my file contains the following:

lalala
foo
DESKTOP-PI3R74I=
bar
foobar

Your code looks like this:

import socket

hostname = socket.gethostname()
print(hostname)  # 'DESKTOP-PI3R74I'

# Abrir o arquivo em modo de leitura
with open('arquivo.txt', 'r') as fd:
    txt = fd.read()  # Ler todo o arquivo

    # Substituir hostname= por hostname=192.168.1.1 em todas as 
    # ocorrências no texto lido
    txt = txt.replace(hostname + '=', hostname + '=192.168.1.1')

# Abrir o arquivo em modo de escrita
with open('arquivo.txt', 'w') as fd:
    fd.write(txt)  # Escrever texto modificado
    
28.06.2018 / 19:17