文件操作(三)——文件的修改两种方式

#文件的修改两种方式:
# 1、读入内存,再写;
# 2、硬盘模式决定,将文件先读出来,写完再另存,边读边写。这样就需要打开两个文件
1 f=open('my_heart_will_go_on','r',encoding='utf-8')
2 f_new=open('my_heart_will_go_on.bak','w',encoding='utf-8')
3 for line in f:
4     if 'Once more you open the door' in line:
5         line=line.replace('Once more you open the door','Once more Easter open the door')#用replace方法替换
6     f_new.write(line)
7 f.close()
8 f_new.close()
View Code
原文地址:https://www.cnblogs.com/pythonkids/p/7676289.html