How to find, check and change file?

Posted on

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()
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"
    linhas_a_escrever += linha
arquivo = open("teste.txt","w")

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


Leave a Reply

Your email address will not be published. Required fields are marked *