rename an image using python python

Lasted updated by @craigaddyman on 20 August 2015

Today I was tasked with renaming over a thousand files, this comes off the back of a recommendation to the client to rename them to be more specific to what they are, so essentially they are changed to their product name from their product code. This is a fairly standard practice and it's something worth doing, especially if your product is fairly visual, as ranking an image is a piece of cake.

Anyway when this was being discussed in a meeting my boss volunteered me to do it. The following is what I ended up with, it's pretty simple really, I did do it the lazy way and formatted the excel document that was provided to me so it would drop straight into a dictionary - If I did it regularly I would write a CSV parser.

import glob
import os

# dict specifying the old and new file names (this contained hundreds LOL)

# iterate over all the files and then dict key values pairs
for files in glob.glob('*.jpg'):
    for old_name, new_name in names.items():
        if old_name in files:
                new = files.replace(old_name, new_name) # if there's a match replace names
                os.rename(files, new) # rename the file
                print files, new # just to make sure it's working
                print 'ERROR!!,', files # to see if there were any errors


Subscribe by email