python批量重命名文件的后缀名

本文介绍了如何使用Python中的正则表达式进行文件名匹配,并通过示例展示了如何根据给定类型实现文件名的转换,包括.m到.h、.m到.c、.h到.m和.c到.m的重命名操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、涉及语法

1、正则表达式

2、文件重命名

二、代码

import os
import re

# 1: m to h
# 2: m to c
# 3: h to m
# 4: c to m
a_Path = "D:/xxx/0_Desktop/xxx/PatckgeTest_demo - h"
a_Type = 3

if(1 == a_Type):
    a_name = '.m'
    b_name = '.h'
elif(2 == a_Type):
    a_name = '.m'
    b_name = '.c'
elif(3 == a_Type):
    a_name = '.h'
    b_name = '.m'
elif(4 == a_Type):
    a_name = '.c'
    b_name = '.m'
else:
    print('error happen')



filelist = os.listdir(a_Path)

print(type(filelist))
newList = []

for i in filelist:

    k = re.split( a_name+'$', i)
    if(len(k) > 1):
        newList.append(i)

print('-------------------------------------')
for i in newList:
    #print(i)
    k = re.split( a_name+'$', i)
    p_newName = k[0] + b_name
    #print(p_newName)

    p_oldFilePath = a_Path + '/' + i
    p_newFilePath = a_Path + '/' + p_newName
    #print(p_oldFilePath)
    #print(p_newFilePath)

    try:
        os.rename(p_oldFilePath, p_newFilePath)
    except Exception as e:
        print(e)
        print('rename file fail\r\n')
    else:
        print('rename file success\r\n')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值