'''
批量修改文件名
例:
修改前:2022-实验22-学生45-front-1121.1618.51.518_501.jpg
修改后:2022_45_front_1121.1618.51.518_501.jpg
'''
import os
path = 'E:\group4\data'
# 获取该目录下所有文件,存入列表中
filelist = os.listdir(path)
for file in filelist:
# 统计字符个数
resoult = {}
for i in file:
resoult[i] = file.count(i)
n = resoult['-'] #统计'-'字符数量
#获取旧文件名(路径+文件名)
old_name = path + os.sep + file# os.sep添加系统分隔符
print(old_name)
str0 = file.split('-')[0]
str1 = ''.join(filter(str.isdigit, file.split('-')[n-2])) # 学生后面的数字
str2 = file.split('-')[n-1]
str3 = file.split('-')[n]
prefix = str0 + '_' + 'student'+str1 + '_' + str2 +'_' + str3
print(prefix)
if os.path.isdir(old_name): #跳过old_name是路径的情况
continue
# 设置新文件名
new_name = path + os.sep + prefix
os.rename(old_name,new_name) #新文件名替换旧文件名