码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-01-13 17:06:41      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:import   ima   %s   enc   pen   批量修改   http   文件名   line   

#-*-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)_写函数,实现修改文件内容

标签:import   ima   %s   enc   pen   批量修改   http   文件名   line   

原文地址:https://www.cnblogs.com/sunnybowen/p/10262723.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!