Search code examples
pythonnaming

Rename multiple file with counting in the front in python


I want to add a serial of number in the front of my file name and start with 001, 002, 003,....999

With the code

count = 1
for i in list:
    os.rename(i, str(count)+'_'+i[0:-4]+'.jpg')
    count += 1

I can get the name start with 1, 2, 3, 4,....999

How to make it start with 001, 002, 003,...to 999?


Solution

  • You can use zfill() and combine it with enumerate():

    for count, i in enumerate(list):
        os.rename(i, str(count+1).zfill(3)+'_'+i[0:-4]+'.jpg')