使用.rename和.endswith

时间:2015-06-15 15:40:02

标签: python rename batch-rename

我一直试图让它发挥作用,但我觉得我错过了一些东西。文件夹中有大量图像,我只需重命名文件名的一部分。例如,我正在尝试将“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

这是我到目前为止所做的,但它只是给我“其他”而不是实际重命名其中任何一个:

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 个答案:

答案 0 :(得分:3)

Python字符串方法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))

请注意,您需要与文件的基本名称匹配,然后在路径的其余部分加入。

答案 1 :(得分:1)

您无需使用.endswith。您可以使用.split拆分图像文件名并检查结果。由于涉及多个后缀字符串,因此我将它们全部放入set以进行快速成员资格测试。

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)