python批量替换文件名
替换关键字
#-*-coding:utf-8-*- import os import re filepath = u'E:\\CMMI4\\07_测试文档' files = os.walk(filepath) name = u'这是替换前的关键字' rename = u'这是替换后的关键字' for folderName, subfolders, filenames in files: # print(filenames) # print(subfolders) # print(folderName) for file in filenames: # print(file) nameRegex = re.compile(r'这是替换前的关键字(.*)') partName = nameRegex.search(file).group(1) # print(partName) newname = rename + partName # print(newname) oldPath = os.path.join(folderName, file) newPath = os.path.join(folderName, newname) os.rename(oldPath, newPath) print('success!')
修改文件后缀,把 .docx 变为 .doc ;
#-*-coding:utf-8-*- import os import re filepath = u'E:\\CMMI4\\07_测试文档' files = os.walk(filepath) for folderName, subfolders, filenames in files: for file in filenames: if file.endswith('.docx'): nameRegex = re.compile(r'(.*).docx') partName = nameRegex.search(file).group(1) newname = partName + '.doc' oldPath = os.path.join(folderName, file) newPath = os.path.join(folderName, newname) os.rename(oldPath, newPath) print('success!')
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步