gpt4 book ai didi

python - 使用 .rename 和 .endswith 重命名多个图像

转载 作者:行者123 更新时间:2023-11-28 22:43:23 25 4
gpt4 key购买 nike

我一直在努力让它发挥作用,但我觉得我错过了什么。文件夹中有大量图像,我只需要重命名部分文件名。例如,我试图将“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 字符串方法 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))

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com