Search code examples
pythonpython-3.xrenameenumerate

How to rename multiple images into two different names?


I need to rename 992 image's name in the folder with Python. The name of the images should change based on their order. For example

current name
image_1 should rename to P1_ES_1
image_2 should rename to P1_ES_2
image_3 should rename to P1_ES_3
image_4 should rename to P1_ED_1
image_5 should rename to P1_ED_2
image_6 should rename to P1_ED_3

and again will repeat the same thing for the next six images just "P" will change such as follows:

image_7 should rename to P2_ES_1
image_8 should rename to P2_ES_2
image_9 should rename to P2_ES_3
image_10 should rename to P2_ED_1
image_11 should rename to P2_ED_2
image_12 should rename to P2_ED_3

the snippet I have already will change the names as attached file displays for the first six images which is not like what I need.enter image description here

here is snippet:

import os
import glob

path = 'F:/my_data/imagesResized/'

def rename_files(): 

 j = 1
 i = 1

 for i, filename in enumerate(glob.glob(path + '*.png')): 

    os.rename(filename[:], os.path.join(path, 'P' + str(i) + '_'+ "ES" + '_' + str(j) + '.png'))

    j += 1

if __name__ == '__main__': 

    rename_files() 

Solution

  • The easiest way is to use the modulo operator to cycle through your indices. You did the right job with enumerate. Another fun fact, use sorted to sort the images accordingly using glob, sometimes, the filenames come in random order:

    fns = sorted(glob.glob(path + '*.png')): 
    
    es_or_ed = 'ED'
    
    for i, fn in enumerate(fns):
        # Check for ED or ES
        if i % 3 == 0 and es_or_ed == 'ES':
            es_or_ed = 'ED'
    
        elif i % 3 == 0 and es_or_ed == 'ED':
            es_or_ed = 'ES'
    
        # Create new filename
        new_fn = 'P{}_{}_{}.png'.format(i // 6 + 1, es_or_ed, i%3+1)
    
        # rename...
        os.rename(fn, os.path.join(path, new_fn))
    

    For random images, that would give you

     old: image_1     new: P1_ES_1
     old: image_2     new: P1_ES_2
     old: image_3     new: P1_ES_3
     old: image_4     new: P1_ED_1
     old: image_5     new: P1_ED_2
     old: image_6     new: P1_ED_3
     old: image_7     new: P2_ES_1
     old: image_8     new: P2_ES_2
     old: image_9     new: P2_ES_3
     old: image_10    new: P2_ED_1
     ...