python rename image in a folder

Question:

I’m trying to rename all files in a folder (suppose the name is already sorted from 0 – 20), I want to rename them starting at a specified number.
It really changes all images’ names but the order is messed up.
Right after it changes the name of 1st image, it jumps to the 10th image before going back to 2nd image.

Is there something wrong with the loop?

for file_name in os.listdir(folder):
    
    source = folder + file_name
    
    destination = folder + str(count) + ".jpg"
  
    os.rename(source, destination)
    count += 1
Asked By: supnep

||

Answers:

From the listdir documentation:

The list is in arbitrary order

You’ll want to apply a natural sort to that returned list to get it in the order you expect. See for example Is there a built in function for string natural sort?

Answered By: Mark Ransom
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.