import os标签:name,extension,后缀,图片格式,action,prefix,增删,path,suffix From: https://www.cnblogs.com/zly324/p/17796464.html
from PIL import Image
def process_images(root_dir, prefix_action, prefix, suffix_action, suffix):
for foldername, subfolders, filenames in os.walk(root_dir):
for filename in filenames:
file_path = os.path.join(foldername, filename)
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
img = Image.open(file_path)
if img.mode == "RGBA":
img = img.convert("RGB")
folder_path, old_name = os.path.split(file_path)
name_without_extension = os.path.splitext(old_name)[0]
# 处理前缀
if prefix_action == "+":
name_without_extension = prefix + name_without_extension
elif prefix_action == "-":
name_without_extension = name_without_extension.replace(prefix, "")
# 处理后缀
if suffix_action == "+":
name_without_extension += suffix
elif suffix_action == "-":
name_without_extension = name_without_extension.replace(suffix, "")
new_name = name_without_extension + ".jpg"
new_file_path = os.path.join(folder_path, new_name)
counter = 1
while os.path.exists(new_file_path):
new_name = name_without_extension + "_" + str(counter) + ".jpg"
new_file_path = os.path.join(folder_path, new_name)
counter += 1
img.save(new_file_path, "JPEG")
os.remove(file_path)
if __name__ == "__main__":
address = input("请输入地址:")
prefix_action = input("请选择增加前缀(+), 还是删除前缀(-) 或 不做操作(直接按Enter):").strip() or None
prefix = input("请输入前缀:") if prefix_action else ""
suffix_action = input("请选择增加后缀(+), 还是删除后缀(-) 或 不做操作(直接按Enter):").strip() or None
suffix = input("请输入后缀:") if suffix_action else ""
process_images(address, prefix_action, prefix, suffix_action, suffix)
print("处理完成!")