Search code examples
pythonfile-iofile-rename

Renaming files with a pattern


Python beginner here.

I have a directory with hundreds of image files named as (in sequence):

002_IMG_001, 002_IMG_002, 002_IMG_003, 002_IMG_N

Now, I am trying to rename those images such that the five files in a row have 'N' from 1:5, that is, every consecutive set of five images get N, 1 to 5. I would also like to stick another string before the number 'N'. This string will keep track of the set of N images, e.g, IMG_001_1, IMG_001_2,.. IMG_001_N, IMG_002_1,IMG_002_2,...IMG_00X_N.

The pseudo code on python 2.7.10 on Mac looks like this:

import os

myDir = "/Users/path/to/dir/"
fileList = os.listdir(myDir)

for filename in fileList :
    #split the images into sets of five each
    newFile = 'IMG_' + '00' + X + '_' + N
        #loop through images and rename
            os.rename(fileName, newFile)

I think I need a condition inside for loop, somthing like:

 if int(filename[9:12]) % 5 == 0

but this would mean, I have to create five separate conditions for 1 to 5, which doesn't seem right. Any hint would be appreciated ?

Edit: It wasn't clear to some what kind of output was required. I am looking for a function to get the final file names like: IMG_001_1, IMG_001_2,...IMG_001_5, IMG_002_1, IMG_002_2,...IMG_002_5,...


Solution

  • I think this should work:

    my_list = ["002_IMG_001", "002_IMG_002", "002_IMG_003", "002_IMG_004", "002_IMG_005",
           "002_IMG_006", "002_IMG_007", "002_IMG_008", "002_IMG_009", "002_IMG_0010",
           "002_IMG_011", "002_IMG_012", "002_IMG_013", "002_IMG_014", "002_IMG_015",
           "002_IMG_016", "002_IMG_017", "002_IMG_018", "002_IMG_019", "002_IMG_0020",
           ]
    fileList.sort()
    
    print("Original list:\n")
    print(fileList)
    
    new_list = []
    
    for index, old_file_name in enumerate(fileList):
        group, subgroup = divmod(index,5)
        group, subgroup = group + 1, subgroup + 1
        new_file_name = "IMG_{0:03d}_{1}".format(group, subgroup)
        new_list.append(new_file_name)
    
        os.rename(old_file_name, new_file_name)
    
    print("\nNew list:\n")
    print (new_list)
    

    Here is the output:

    Original list:
    
    ['002_IMG_001', '002_IMG_002', '002_IMG_003', '002_IMG_004', '002_IMG_005', 
    '002_IMG_006', '002_IMG_007', '002_IMG_008', '002_IMG_009', '002_IMG_0010', 
    '002_IMG_011', '002_IMG_012', '002_IMG_013', '002_IMG_014', '002_IMG_015', 
    '002_IMG_016', '002_IMG_017', '002_IMG_018', '002_IMG_019', '002_IMG_0020']
    
    New list:
    
    ['IMG_001_1', 'IMG_001_2', 'IMG_001_3', 'IMG_001_4', 'IMG_001_5', 
    'IMG_002_1', 'IMG_002_2', 'IMG_002_3', 'IMG_002_4', 'IMG_002_5', 
    'IMG_003_1', 'IMG_003_2', 'IMG_003_3', 'IMG_003_4', 'IMG_003_5', 
    'IMG_004_1', 'IMG_004_2', 'IMG_004_3', 'IMG_004_4', 'IMG_004_5']