python批量筛选出文件,python查找并批量替换配置文件内容

缘由和需求大概描述是这样,有个提供接口服务老站点A要下线,但还有站点B还在调用这个接口,要切换到新接口,由于站点B历史悠久估计有10年时间,经很多人手站点代码和文件有5.4G大小内有很多目录文件。现在要站点B内所有目录下所有'*.php' 文件内接口url为"http://xx.xxxx.com/outer/Interface.php?w=$word&n=$num&out=xml"替换为"http://xx.xxxx.com/?c=api&s=$word&out=xml&page=1&pagesize=$num" ;当时想使用shell的find,for,sed来处理,由于url里面有很多特殊字符,即使我做了转义了还是无法使用sed进行替换,暂没时间查很多sed的资料,就使用熟悉的python来进行处理。

在我调试的时候发现,有目录文件大小为5.5G的文件使用os.walk()查找所有下"*.php"时使用4分多钟,python调用shell的find命令时才用40秒。下面是代码,希望脚本的思路和写法给大家一些提示或帮助。(如果哪位有sed替换有特殊字符url,望不吝赐教)

#/usr/bin/python

#coding:utf-8

"""

To update all directory php file for new interfaces url

"""

__author__ = 'Qfeian@20140307'

import fileinput

import os

def replace_str(filepath, old, new):

for line in fileinput.input(filepath, inplace=True):

line = line.rstrip().replace(old, new)

print line

old_str = """http://xx.xxxx.com/outer/Interface.php?w=$word&n=$num&out=xml"""

new_str = """http://xx.xxxx.com/?c=api&s=$word&out=xml&page=1&pagesize=$num"""

"""

pattern = '.php'

rootdir = '/data/app/ms.www.xxxx.com'

for root, subfolders, files in os.walk(rootdir):

for name in files:

if name.find(pattern) != -1:

filedir = os.path.join(root, name)

#print filedir

replace_str(filedir, old_str, new_str)

"""

if __name__ == "__main__":

cmd = "find /data/app/ms.www.xxxx.com -name '*.php' "

filedirlist = os.popen(cmd)

for filedir in filedirlist.readlines():

filedir = filedir.strip('\n')#去掉每行末尾的换行符

#print filedir

replace_str(filedir, old_str, new_str)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值