Search code examples
pythonrenamebatch-rename

Renaming multiple images with .rename and .endswith


I've been trying to get this to work, but I feel like I'm missing something. There is a large collection of images in a folder that I need to rename just part of the filename. For example, I'm trying to rename the "RJ_200", "RJ_600", and "RJ_60"1 all to the same "RJ_500", while keeping the rest of the filename intact.

Image01.Food.RJ_200.jpg
Image02.Food.RJ_200.jpg
Image03.Basket.RJ_600.jpg
Image04.Basket.RJ_600.jpg
Image05.Cup.RJ_601.jpg
Image06.Cup.RJ_602.jpg

This is what I have so far, but it keeps just giving me the "else" instead of actually renaming any of them:

import os
import fnmatch
import sys

user_profile = os.environ['USERPROFILE']
dir = user_profile + "\Desktop" + "\Working"

print (os.listdir(dir))

for images in dir:
    if images.endswith("RJ_***.jpg"):
        os.rename("RJ_***.jpg", "RJ_500.jpg")
    else:
        print ("Arg!")

Solution

  • The Python string method endswith does not do pattern-matching with *, so you're looking for filenames which explicitly include the asterisk character and not finding any. Try using regular expressions to match your filenames and then building your target filename explicitly:

    import os
    import re
    patt = r'RJ_\d\d\d'
    
    user_profile = os.environ['USERPROFILE']
    path = os.path.join(user_profile, "Desktop", "Working")
    image_files = os.listdir(path)
    
    for filename in image_files:
        flds = filename.split('.')
        try:
            frag = flds[2]
        except IndexError:
            continue
        if re.match(patt, flds[2]):
            from_name = os.path.join(path, filename)
            to_name = '.'.join([flds[0], flds[1], 'RJ_500', 'jpg'])
            os.rename(from_name, os.path.join(path, to_name))
    

    Note that you need to do your matching with the file's basename and join on the rest of the path later.