Renaming multiple images with .rename and .endswith

752 views Asked by At

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!")
2

There are 2 answers

6
xnx On BEST ANSWER

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.

3
martineau On

You don't need to use .endswith. You can split the image file name up using .split and check the results. Since there are several suffix strings involved, I've put them all into a set for fast membership testing.

import os
import re
import sys

suffixes = {"RJ_200", "RJ_600", "RJ_601"}
new_suffix = "RJ_500"

user_profile = os.environ["USERPROFILE"]
dir = os.path.join(user_profile, "Desktop", "Working")

for image_name in os.listdir(dir):
    pieces = image_name.split(".")
    if pieces[2] in suffixes:
        from_path = os.path.join(dir, image_name)
        new_name = ".".join([pieces[0], pieces[1], new_suffix, pieces[3]])
        to_path = os.path.join(dir, new_name)
        print("renaming {} to {}".format(from_path, to_path))
        os.rename(from_path, to_path)