Question :
I have a doubt that I am new to python.
I have a file for example:
bla bla bla
bla bla bla 5
bla bla bla 846:545
energia 3
I intend to read from the teste.txt
file the energy information.
Of which I want to check the number that is, and the number 3, and if need be, change it to number 5.
Answer :
You will have to read line by line and then rewrite the file:
arquivo = open("teste.txt","r")
linhas = arquivo.readlines()
arquivo.close()
linhas_a_escrever = ''
for linha in linhas:
if "energia" in linha:
lixo,valor_energia = linha.split(" ")
if int(valor_energia) == 3:
linhas_a_escrever += "energia 5n"
continue
linhas_a_escrever += linha
arquivo = open("teste.txt","w")
arquivo.write(linhas_a_escrever)
arquivo.close()
I imagine this is what you want to do.
A solution creating a new file with the changed value:
novo = open('novo_ficheiro.txt', 'w')
with open('ficheiro.txt', 'r') as ficheiro:
for linha in ficheiro:
nova_linha = linha
if 'energia' in linha:
nova_linha = 'energia %i' % 4
novo.write(nova_linha)
novo.close()