Python os 批量修改文件名 正则表达式

# -*- coding: utf-8 -*-
import os
import re
#设定文件路径
path=r'D:\郭鹏历届真题解析2007-2020'
i=1
#对目录下的文件进行遍历
for file in os.listdir(path):
#判断是否是文件
    file_name=os.path.join(path,file)
    if os.path.isfile(os.path.join(path,file))==True:
        #设置新文件名
        year=re.search(r"(\d{4})",file).group(0)
        jie=int(year)-1983
        print(year,jie)

        file2=file.replace(". ","",1)
        new_name=year+""+str(jie)+""+file2
        os.rename(os.path.join(path,file),os.path.join(path,new_name))
        print(new_name)

 

posted @ 2021-05-14 16:57  沭水之虾  阅读(236)  评论(0编辑  收藏  举报