替換關鍵字測試
#-*-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 ;spa
#-*-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!')