文件修改,我们可以不用讲一个文件全部都进行读取,然后放入内存,如果文件过大,容易造成内存的
内存溢出问题
因此我们可以便读取边进行修改操作
f=open("old.txt","r",encoding="utf-8")
f_new=open("new.txt","w",encoding="utf-8")
for line in f:
if "微笑在天上" in line:
line=line.replace("微笑在天上","开心在心中");
f_new.write(line)
f.close()
f_new.close()
同时我们也可以将关闭文件的动作交给With来实现:
with open("new.txt","w",encoding="utf-8") as f:
for line in f:
print(line)