Reputation:
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
Upvotes: 0
Views: 173
Reputation: 308111
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?
Upvotes: 1