# -*- coding:utf-8 -*- import os,re rootdir = r"D:\ideaspace" for parent,dirnames,filenames in os.walk(rootdir):#三个参数:分别返回1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字 for filename in filenames:#文件名 print("文件===", filename) new_strcompile = re.compile('匹配位置') newname = new_strcompile.sub('', filename) if filename.count("匹配位置"): os.rename(os.path.join(parent,filename),os.path.join(parent,newname))#文件重命名 for dir in dirnames: print("目录===",dir) new_strcompile = re.compile('匹配位置') newdir = new_strcompile.sub('', dir) if dir.count("匹配位置"): os.rename(os.path.join(parent, dir), os.path.join(parent, newdir)) # 文件夹重命名