How to rename multiple without randomizing the order of the files

I am trying to rename like 1k+ images however I want to keep their order.

Currently what I am doing works but randomizes the order of the images

# Python program to rename all file
# names in your directory
import os

os.chdir('Box Images - Renamed')
print(os.getcwd())

for count, f in enumerate(os.listdir()):
    f_name, f_ext = os.path.splitext(f)
    f_name = "" + str(count)

    new_name = f'{f_name}{f_ext}'
    os.rename(f, new_name)

what I want to do is keep their order, e.g. the first image in the folder starts with "Box - #1.png" and the next one "Box - #2.png", "Box - #3.png", etc. By renaming them I want that to be 0.png, 1.png, 2.png without losing the image that previously was there. When I run the script that order is randomized what was on the image Box - #3.png is not anymore on 2.png and etc.


The important concept to convey here is that your images aren't actually in any order in the first place.

Tools like the shell (when evaluating *.png into a list of matching names) will impose an order by sorting in the current locale's character collation order, but that order isn't reliably enforced at the filesystem layer; and os.listdir() is just passing through what the filesystem layer returns without modifying it at all.

You can impose your own order by passing content through sorted() before it gets to enumerate():

for count, f in enumerate(sorted(os.listdir())):

...or, better, you can create a key by extracting the number and parsing it as a number (which will ensure that your code understands that 10 is greater than 2, whereas a character-by-character comparison makes 2 sort after 10):

import re

numberKey_re = re.compile(r'[#](\d+)')
def numberKey(filename):
    match = numberKey_re.search(filename)
    if match is None:
      return (None, filename)
    else:
      return (int(match.groups(1)), filename)

for count, f in enumerate(sorted(os.listdir(), key=numberKey)):