I have a loop to add filenames in a Python script. When the number of files reach 5000+, this is causing high CPU usage.
Is there any way to avoid this or make this more efficient?
number = 1
while True:
fname = "Capture_" + str(number) + ".jpg"
if not os.path.exists(fname):
break
number = number + 1
DoSomething(fname)
Ok. Based on the comments, i came up with this code. If i only did max(glob.glob('Capture_*.jpg'))
then i only get Capture_999.jpg
if os.path.exists('Capture_1.jpg'):
number = max(glob.glob('Capture*'), key=os.path.getctime).replace('Capture_', '').replace('.jpg', '')
number = str(int(number) + 1)
else:
number = '1'
fname = 'Capture_' + number + '.jpg'
But it seems to be again causing high CPU usage. Is it possible to make this more efficient?
I finally resolved with this simply with : fname = 'Capture_' + str(len(os.listdir(Path)) + 1) + '.jpg'