import os #os.chroot(path)
#用with会判断这个文件什么时候可以关闭,它会自动关闭,不需要手动关闭
#方法一:适合小文件
#思路:文件里面有很多这个要替换的内容,需要把原来的文件都拿出来,然后替换成新的内容,把原来的都删除
with open('abc','r+',encoding='utf-8') as fw:#如果用r+,光标在最前面不用seek
# fw.seek(0)
res =fw.read()
res_read =res.replace('AB1','AB2')
# print(res_read)
fw.seek(0)
fw.truncate()#清空文件
fw.write(res_read)
#方法二:适合大文件,还是要一行一行处理
#打开两个文件
with open('user') as fr,open('.user','w',encoding='utf-8')as fw:
for line in fr:
res=line.replace('abc','ABC')
fw.write(res)
print(res)
os.remove('user')
os.rename('.user','user')
#split vertically分屏查看