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!')