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
.
Artur the question is not very clear, da para melhorar? vlw!
– Paulo Vieira