class ReplaceFile: def replaceFile(): beReplaced = input('请输入需要被替换的词语:') replaced = input('请输入替换的词语:') with open(r'C:\Users\Lenovo\Desktop\test.txt','r') as file: readFile = file.read() newStr = readFile.replace(beReplaced,replaced) with open(r'C:\Users\Lenovo\Desktop\test.txt','w') as newFile: newFile.write(newStr) if __name__ == '__main__': ReplaceFile.replaceFile()