How can I increment numbers on saved files in Python?
Originally posted on my Python Wiki.
This is a function I had made for my BubblePaint program in PyGame. In a nutshell, it will save the screen to a png
image, and increment the filename with each image in the dir. User can keep saving images, and this will keep incrementing the number of the newly saved file.
import glob, os, re def saveImage(): """ Save the current image to the working directory of the program. """ currentImages = glob.glob("*.png") numList = [0] for img in currentImages: i = os.path.splitext(img)[0] try: num = re.findall('[0-9]+$', i)[0] numList.append(int(num)) except IndexError: pass numList = sorted(numList) newNum = numList[-1]+1 saveName = 'bubblePaint.%04d.png' % newNum print "Saving %s" % saveName pygame.image.save(screen, saveName)
Will save out files like this:
bubblePaint.0001.png bubblePaint.0002.png etc...
It would be more efficient to use max(numList) instead of sorted(numList)[-1].
Good tip, I’d not thought of that. I don’t think I use min\max as much as I should…