def updateFile(file,old_str,new_str):
file_data = ""
with open(file, "r") as f:
for line in f:
line = line.replace(old_str,new_str)
file_data += line
with open(file,"w") as f:
f.write(file_data)
updateFile(r'C:\Users\mage\Desktop\新建文本文档.txt','I am very happy.','but I am unhappy')
修改前,注意,只能修改非中文的内容

修改后

注意:这段代码若file不存在,则会自动创建一个
with open(file,"w") as f:
f.write(file_data)
这篇博客介绍了如何修改txt文件中的非中文内容,特别指出在文件不存在的情况下,代码会自动创建新文件。
703

被折叠的 条评论
为什么被折叠?



