手把手教你完成将文件夹里面的图片.png格式转化为.jpg格式--基于python学习,用到了正则表达式的知识

  new_name = re.sub(r"png$", "jpg", old_name)

这行代码利用了正则表达式,第一个参数r"png$"表示要被替换的字符,第二个参数jpg为替换后的字符,old_name指的是字符串变量

 

 

import os
import re
import shutil

def rename_images(folder_path):
    #检查文件夹是否存在
    if not os.path.exists(folder_path):
        print(f"文件夹‘{folder_path}’不存在。")
        return
    #遍历文件夹中的文件
    file_list=os.listdir(folder_path)
    image_files=[ f for f in file_list ]
    for old_name in image_files:
        new_name = re.sub(r"png$", "jpg", old_name)
        #重命名文件
        old_path=os.path.join(folder_path,old_name)
        new_path=os.path.join(folder_path,new_name)
        shutil.move(old_path,new_path)
        print(f"重命名文件:'{old_name}'->'{new_name}'")

folder_path="D:\\OneDrive\\Desktop\\D"
rename_images(folder_path)

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值