Write to a. txt file with for loop in Python

Asked

Viewed 37 times

1

I need a file . txt to save the last generated serial, for the next time that file is executed to be read and continue sequencing. That is, if the last serial(serial2) generated is the number 6 I want to save the number 6 in txt so that in the next execution of the code it starts in 6. I am using txt as a "Database".

def GerarSerial(start_at=int(open('ultimaos.txt', 'r').readlines(0)[0])+1):
    serial = f'{start_at:0>5}'
    serial2 = f'{start_at+1:0>5}'
    with open('ultimaos.txt', 'w') as ultimaosarquivo:
        ultimaosarquivo.write(serial2)
    with open('ultimaos.txt', 'r') as ultimaosarquivo:
        ultima_os = ultimaosarquivo.readlines(0)[0]
    return f'{ultima_os:0>5}'

if __name__ == '__main__':
    for x in range(3):
        GerarSerial()
        print(GerarSerial())

ultimaos.txt:

00006

But when executing the code it only repeats the value 3 times.

  • 1

    Artur the question is not very clear, da para melhorar? vlw!

1 answer

0


The problem is that you set a value default for the parameter start_at. And according to the documentation, this value is evaluated only once, when the function is created, and then no longer changes:

Default Parameter values are evaluated from left to right when the Function Definition is executed. This Means that the Expression is evaluated Once, when the Function is defined, and that the same "pre-computed" value is used for each call.

That is, when you create the function, the start_at will have the default value based on the current content of the file, summed with 1. And for all calls made without any arguments, will be used the initial value that it had. That’s why, no matter how many times you call the function, the same value is being used.

So remove this parameter. Inside the function you have to always read the current value and add 1:

def GerarSerial(arquivo='ultimaos.txt'): # acho que faz mais sentido o nome do arquivo ser um parâmetro
    try:
        # tenta ler o arquivo
        with open(arquivo, 'r') as arq:
            atual = int(arq.read()) # como o arquivo só tem uma linha, lê tudo
    except OSError:
        # se o arquivo não existe, começa um novo serial
        # mas também poderia dar erro, você decide o que faz mais sentido para o seu caso
        atual = 0

    # calcula o novo serial (no caso, soma 1 com o atual)
    serial = f'{atual + 1:0>5}'
    with open(arquivo, 'w') as arq: # atualiza o arquivo
        arq.write(serial)
    return serial

for _ in range(3):
    print(GerarSerial())

Since the file always has only one line, it does not need readlines to read all the lines and then pick up the first one. Just use read to read everything (but also could be readline() - singular - to read the first line).

Of course I had to check if the content is even a number, but the general idea is this: if the file does not exist, starts a new serial (but could give error, you decide what makes more sense for your case), and if it exists, read the content of it.

Then just add 1 and write the new serial to the file, and return this serial. And see that you do not need to open the file again to read what you just saved, because this is already in the variable serial.

Browser other questions tagged

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