Ayyan Khan
Ayyan Khan

Reputation: 507

rename the files with same names in different folders

I want to copy all the images in different folders into one folder. But the issue I am facing is files in different folders have same names e.g

Folder: A123 Front A123 Black.jpg , A123 Pink.jpg , A123 Red.jpg

Folder: A123 Back A123 Black.jpg , A123 Pink.jpg , A123 Red.jpg

What I want to achieve is all files in one folder and named something like,

A123_1.jpg ,A123_2.jpg , A123_3.jpg , A123_4.jpg , A123_5.jpg , A123_6.jpg

Note, A123 is product code and so I want Product code with numbr of images with that product code appended with underscore.

These are in 1000s and in sub sub directories, I have simplified it for convenience.

I have written following code , to go into directories and sub directories.

import os
def replace(folder_path): 
    for path, subdirs, files in os.walk(folder_path):
       c=len(files)
       for name in files:
           if 'Thumb' in name:
               continue

            file_path = os.path.join(path,name)
            print(file_path)
            new_name = os.path.join(path,strname)
            os.rename(file_path,strname)
            c-=1


print('Starting . . . ')
replace('files/GILDAN')

But I am not sure how should be renaming.

Upvotes: 2

Views: 94

Answers (1)

rahlf23
rahlf23

Reputation: 9019

To count the number of existing files in the destination directory, you could use a regex or simply use a list comprehension like:

image_no = len([i for i in os.listdir(destination_path) if i.startswith(product_code)])

Use image_no to set the image number in your rename command:

os.rename(file_path, product_code + '_' + str(image_no))

Upvotes: 2

Related Questions