python 根据后缀名修改图片名字并重新保存

import os.path as osp
import os
import shutil

path = "/待修改图片路径/data/0203_sum/"
index = 0
for root, dirs, files in os.walk(path):
    print("root:",root)
    print("dirs:",dirs)
    #print("files:",files)
    for name in files:       
        if osp.join(root, name).endswith("_F.jpg"):
            #print("name:",name)
            rename = name.replace("_F.jpg","_L.jpg")
            #print("rename:",rename)
            new_path = root.replace("0203_sum","0203_sum_copy_2")  
            os.makedirs(new_path, exist_ok=True)
            shutil.copy(root + "/" + name, new_path + "/" + rename)  
            print("copy %s to new path:"%(name) + new_path + "/" + rename)       
            #os.rename(root + "/" + name, root + "/" + rename)
            index = index + 1
        elif osp.join(root, name).endswith("_L.jpg"):
            #print("name:",name)
            rename = name.replace("_L.jpg","_F.jpg")
            #print("rename:",rename) 
            new_path = root.replace("0203_sum","0203_sum_copy_2")  
            os.makedirs(new_path, exist_ok=True)
            shutil.copy(root + "/" + name, new_path + "/" + rename)  
            print("copy %s to new path:"%(name) + new_path + "/" + rename)       
            #os.rename(root + "/" + name, root + "/" + rename)
            index = index + 1
        elif osp.join(root, name).endswith("_F.png"):
            #print("name:",name)
            rename = name.replace("_F.png","_L.png")
            #print("rename:",rename) 
            new_path = root.replace("0203_sum","0203_sum_copy_2")  
            os.makedirs(new_path, exist_ok=True)
            shutil.copy(root + "/" + name, new_path + "/" + rename)  
            print("copy %s to new path:"%(name) + new_path + "/" + rename)      
            #os.rename(root + "/" + name, root + "/" + rename)
            index = index + 1
        elif osp.join(root, name).endswith("_L.png"):
            #print("name:",name)
            rename = name.replace("_L.png","_F.png")
            #print("rename:",rename) 
            new_path = root.replace("0203_sum","0203_sum_copy_2")  
            os.makedirs(new_path, exist_ok=True)
            shutil.copy(root + "/" + name, new_path + "/" + rename)  
            print("copy %s to new path:"%(name) + new_path + "/" + rename)       
            #os.rename(root + "/" + name, root + "/" + rename)
            index = index + 1
        else:
            print("no F or L")
            new_path = root.replace("0203_sum","0203_sum_copy_2")
            os.makedirs(new_path, exist_ok=True)
            shutil.copy(root + "/" + name, new_path + "/" + name)  
            print("copy %s to new path:"%(name) + new_path + "/" + name)
            index = index + 1
print("down 共修改%s张图"%(index))
    原文作者:yz66666666
    原文地址: https://blog.csdn.net/yz66666666/article/details/124293917
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞