文件的改
#文件的改
1,打开源文件,产生文件句柄
2,创建新文件,产生文件句柄
3,读取原文件,进行修改,写入新文件
4,将原文件删除
5,新文件重新命名原文件
引入文件 import os
import os
with open('lo',encoding='utf-8') as f1,\
open('lo.bak',encoding='utf-8',mode='w') as f2:
old_content=f1.read()
new_content=old_content.replace('alex','男生')
f2.write(new_content)
os.remove('lo')
os.rename('lo.bak','lo')
with open('lo',encoding='utf-8') as f1,\
open('lo.bak',encoding='utf-8',mode='w') as f2:
for line in f1:
new_line=line.replace('男生','alex')
f2.write(new_line)
os.remove('lo')
os.rename('lo.bak','lo')