Head of Digital Marketing @Bronco. Lover of Python and Data.

Rename An Image Using Python

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)
names = { 'SOME PRODUCT CODE':'SOME PRODUCT NAME',}

# 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:
            try:
                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
            except:
                print 'ERROR!!,', files # to see if there were any errors


Give Your Inbox Some Love


What You'll get?
  • Posts like this delivered straight to your inbox!
  • Nothing else.
Comment Policy

Any code snippets more than a line or 2, please include as a link to a gist

comments powered by Disqus