How to find, check and change file?

Asked

Viewed 355 times

3

I have a question about being new to the 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 file teste.txt the energy information. Of which I want to check the number that is, and.g the number 3, and if necessary change it to the number 5.

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 that’s what you wish to do.

  • 1

    Thank you, this is exactly what I wanted, I was having trouble validating and rewriting the file. I’ve noticed my mistake thanks to you.

2

A solution creating a new file with the value changed:

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()
  • 2

    Thank you very much for your help and for your availability. Your reply this correct I just preferred the version of Felipe Avelar.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.