How to find, check and change file?

3

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.

    
asked by anonymous 29.06.2015 / 13:21

2 answers

3

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 5\n"
           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.

    
29.06.2015 / 14:51
2

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()
    
29.06.2015 / 14:54