import os def alter(file,old_str,new_str): with open(file, "r", encoding="utf-8") as f1,open("%s.bak" % file, "w", encoding="utf-8") as f2: for lin in f1: if old_str in lin: lin = lin.replace(old_str, new_str) f2.write(lin) os.remove(file) os.rename("%s.bak" % file, file) dest = "/home/ubt/PROCESS_DATA/0423_MIX/shuanghuitaishikaochang48g-weilongdamianjinxiangla65g" #文档的路径 for root, dirs, files in os.walk(dest): for file in files: if file.endswith('.xml'): print(file) alter('/home/ubt/PROCESS_DATA/0423_MIX/shuanghuitaishikaochang48g-weilongdamianjinxiangla65g/{}'.format(file), "weilongdamianjinxiangla65gw", "weilongdamianjinxiangla65g")