Home > Net >  How to generate auto increment in a folder in python?
How to generate auto increment in a folder in python?

Time:03-09

I am new to Python. Anyone help with how to generate auto-increment like B00001, B00002, B00003...... which can autosave the excel file name with a button in a specific folder.

I have tried with

global numXlsx
numXlsx = 1
wb.save(f'invoice/B{numXlsx}.xlsx')
numXlsx  = 1

But when I click the button for few times with different data, it still keeps overwriting the B1.xlsx file. Anyone help with this :)

CodePudding user response:

You can try using a global variable and incrementing it everytime. Try with something like: (inizialize it to 0)

global numXlsx # this is like your counter variable)
wb.save(f'folder/B{numXlsx}.xlsx')
numXlsx  = 1 # Incrementing the variable so it does not overwrite the file as your code is doing

Have a nice day!

CodePudding user response:

It sounds like the biggest problem you're having is that each button click is re-starting the execution of your python script, so using a global variable won't work since that doesn't persist across executions. In this case, I'd suggest using something like the pickle module to store and reload your counter value each time you execute your script. Using that module, your solution could look something like this:

import pickle
from pathlib import Path

# creates file if it doesn't exist
myfile = Path("save.p")
myfile.touch(exist_ok=True)

persisted = {}
with (open(myfile, "rb")) as f:
    try:
        persisted = pickle.load(f)
    except EOFError:
        print("file was empty, nothing to load")

# use get() to avoid KeyError if key doesn't exist
if persisted.get('counter') is None:
    persisted['counter'] = 1

wb.save(f"invoice/B{persisted.get('counter')}.xlsx")
persisted['counter']  = 1

# save everything back into the same file to be used next execution
pickle.dump(persisted, open(myfile, "wb"))

BONUS: If you want the count to be padded with zeros in the filename, use persisted.get('counter'):05d in the curly brackets when saving the file. The 5 indicates you want the resulting value to be at least 5 characters long, so for example 2 would become 00002 and 111 would become 00111.

  • Related