python批量重命名文件的后缀名
程序员文章站
2022-07-02 21:06:01
...
一、涉及语法
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')
上一篇: 如何实现AM解调