Python(69)_写函数,实现修改文件内容

Posted sunnybowen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python(69)_写函数,实现修改文件内容相关的知识,希望对你有一定的参考价值。

#-*-coding:utf-8-*-
import os
‘‘‘
写函数,用户传入修改的文件名,与修改的内容
执行函数,完成整个文件的批量修改操作
‘‘‘
def func(filename,old,new):
    with open(filename,encoding=utf-8) as f,open(%s.bak%filename,w,encoding=utf-8) as f2:
        for line in  f:
            if old in line:
                line = line.replace(old,new)
         #写文件
            f2.write(line)
        os.remove(filename)
        os.replace(%s.bak%filename,filename)

func(log.txt,bowen,Love)

技术分享图片

 

以上是关于Python(69)_写函数,实现修改文件内容的主要内容,如果未能解决你的问题,请参考以下文章