2
That question is a continuation of this here
As previously reported, I have a script that does a txt search for a keyword (APPLE) and if it is true, it alters another part ("00" or "01" or "02") of that same TXT, to illustrate, I will follow with these three lines:
123456 BANANA 00 SP
123457 MACA 01 RJ
123458 PERA 02 MG
It turns out that these three lines are part of the same "header".
The code that is already doing this is this (the number of positions does not reflect with reality, it is only an example, but in the real file they have a layout):
import shutil, tempfile
# lê do arquivo e escreve em outro arquivo temporário
with open('teste.txt', 'r') as arquivo, \
tempfile.NamedTemporaryFile('w', delete=False) as out:
for linha in arquivo:
codigo = linha[07:14] #PESQUISA POR MAÇÃ
if codigo == 'MACA':
print("ACHOU, CODIGO: " + codigo)
linha = linha[:14] + "22" + linha[16:] # remontar a linha com a alteração
else:
print("NÃO ACHOU, CÓDIGO: " + codigo)
out.write(linha) # escreve no arquivo temporário
# move o arquivo temporário para o original
shutil.move(out.name, 'teste.txt')
But there is a problem of logic in this solution, because my reality is that second line i find the "APPLE", I will not change the same line, and yes to top line, that belongs to "BANANA" and that my code has already passed. So the result I hope if the script ends is:
123456 BANANA 22 SP
123457 MACA 01 RJ
123458 PERA 02 MG
UPDATE
The solution I followed then was: create a list and keep adding my lines in it, so I can return a position if necessary, and it was more or less like this:
import shutil, tempfile
saida = []
# lê do arquivo e escreve em outro arquivo temporário
with open('teste.txt', 'r') as arquivo, \
tempfile.NamedTemporaryFile('w', delete=False) as out:
for i,linha in enumerate(arquivo):
saida.append(linha)
saidaLinha = saida[i]
codigo = linha[07:14]
if codigo == 'MACA':
print("ACHOU, CODIGO: " + codigo)
saidaLinha = saida[i-1][:14] + "22" + saida[i-1][16:]
out.write(saidaLinha)
print('linha alterada: '+saidaLinha)
else:
print("NÃO ACHOU, CÓDIGO: " + codigo)
out.write(linha)
# move o arquivo temporário para o original
shutil.move(out.name, 'teste.txt')
However, my output is repeating the first line without ever changing, for example like this:
123456 BANANA 01 SP 123456 BANANA 22 SP 123457 MACA 01 RJ 123458 PERA 02 MG
Does anyone know how to fix this part?
So man, first you need to fix your code indentation. In Python when indentation is wrong, strange things happen. Also note that you keep calling
out.write
in all iterations. Thus, the list is uselesssaida
, because at the end you are not writing it. Do not write in the output file inside the main loop. First you write insaida
, and after the main loop you write all the content ofsaida
in your file.– Allan Juan
How to correctly identify: https://pt.wikibooks.org/wiki/Python/Conceitos_b%C3%A1sicos/Indenta%C3%A7%C3%A3o
– Allan Juan