f=open("E:\\python\\%s"%file_name,encoding="UTF-8") pastword=input("请输入需要替换的内容:") dict1={} num=0 list1=[] for i in f.read(): if i==pastword: dict1[num]=i list1.append(num) num+=1 print("本文件共有%s个%s"%(len(dict1),pastword)) newbook=f.read() neword=input("请输入新的内容:") newbook=newbook.replace(pastword,neword) f1=open("E:\\python\\%s"%file_name,"w",encoding="UTF-8") f1.write(newbook) f1.close() print("写入成功!") f.close()