我一直在试着让它工作,但我觉得我好像错过了什么。文件夹中有大量图像,我只需要重命名文件名的一部分。例如,我试图将“RJ_200”、“RJ_600”和“RJ_60”1重命名为相同的“RJ_500”,同时保持文件名的其余部分不变。

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

这就是我目前所拥有的,但它一直只给我“else”,而不是实际重命名它们中的任何一个:
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!")

最佳答案

Python string方法endswith不与*进行模式匹配,因此您要查找的文件名显式包含星号字符,但找不到任何文件名。
尝试使用正则表达式匹配文件名,然后显式构建目标文件名:

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))

注意,您需要与文件的basename进行匹配,然后在路径的其余部分加入。

关于python - 使用.rename和.endswith重命名多个图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30849343/

10-15 02:30