day4_修改文件

修改文件有两种方式:一种是把文件的全部内容都读到内存中,然后把原有的文件内容清空,重新写新的内容;第二种是把修改后的文件内容写到一个新的文件中

第一种:一次性把文件全部读到,读到内存这个能,这种文件小没什么问题,大文件不好。

实例1:

#1、简单、粗暴直接的,一下这个方式有点儿麻烦,打开文件两次
f = open('file.txt','r',encoding='utf-8')
res = f.read().replace('总是','zongshi')  #替换内容,生成新文件
f.close()
f = open('file.txt','w',encoding='utf-8')
f.write(res)
f.flush()  #立即把缓冲区里面的内容,写到磁盘上,达到立即生效的效果
f.close()

实例2:a+模式修改

f = open('file.txt','a+',encoding='utf-8')
f.seek(0)     #因为是a+模式,指针在最后,所以移到最前面
res = f.read().replace('','NI')
f.seek(0)   #读完后文件指针又到最后面,所以再移到最前面
f.truncate() #清空文件里面的内容
f.write(res)  #写入
f.close()

实例3:r+模式修改

f = open('file.txt','r+',encoding='utf-8')
res = f.read().replace('','WO')
f.seek(0)
f.write(res)  #自动清空原内容,写入新内容

第二种 :循环读取每一行,有需要改的就改内容,再逐行写入新文件,最后删除旧文件,新文件名改成就文件名

#读每一行后写入新文件,然后删除旧文件,再把新文件改成旧文件名字,需要导入os模块
import os #导入os模块
f = open('file','r',encoding='utf-8')
f2 = open('file_bat.txt','w',encoding='utf-8') #再打开一个文件,一直处于打开状态,所以w模式不会覆盖,会接着往后面写
for line in f:
    newline = line.replace('一点','两点')  #将文件中的一点改成两点
    f2.write(newline) #写入新文件
f.close() #关闭文件
f2.close() #关闭文件
os.remove('file')  #删除file这个文件
os.rename('file_bat.txt','file') #将新文件名字改成file

with写法:

with open('file.txt',encoding='utf-8') as f, open('file.txt.bak','w',encoding='utf-8') as f2:#打开多个文件
    for line in f:
        new_line = line.replace('二点','一点')
        f2.write(new_line)

os.remove('file.txt')
os.rename('file.txt.bak','file.txt')

猜你喜欢

转载自www.cnblogs.com/once-again/p/9574078.html
今日推荐