python查找替换(二)
场景:
在特定目录下部分配置文件中的key/value值需进行替换.
目录:e:\doc
文件数:三个,分别是1.properties,2.properties,3.properties,
用于替换的值保存在mysql数据中:clb_config
代码实现:
__author__ = 'Administrator'
#encoding: UTF-8
import time,MySQLdb
import fnmatch
import re,os
#从数据库获得目标key/value
conn=MySQLdb.connect(host="192.168.1.23",user="myuser",passwd="123456",db="manage",charset="utf8")
cursor = conn.cursor()
#cursor.execute("select key,value from manage_config")
#列出特定目录下的所有配置文件
filelist = []
for file in os.listdir(r'E:\doc'):
if fnmatch.fnmatch(file, '*.properties'):
filelist.append(file)
#切换到配置文件目录
source = "E:\doc"
os.chdir(source)
#逐个查找从当前目录下的各个配置文件key列表
for thisfile in filelist:
fd=open(thisfile)
devconfigfile = fd.read()
print "First For,file is %s" %(thisfile)
p = re.compile("(.*)=") #实例化正则表达式
keylist = p.findall(devconfigfile) #获得原始key列表
fd.close
#从数据库中找到当前项目的所有key/value,并对当前配置文件进行value替换
sql="select key,value from clb_config"
for filekey in keylist:
filekey = filekey.replace(" ","") #去掉空格
print " Second For,filekey is %s" %(filekey)
cursor.execute(sql) #以重新执行sql代替恢复游标
for row in cursor.fetchall(): #从sql结果集中逐行取key/value对
dbkey=row[0]
dbvalue=row[1]
if filekey == dbkey:
s=[filekey,dbvalue] #合并出新key/value值
newvalue='='.join(s)
#print "---------------- %s file ------------------" %(thisfile)
print " Third For,filekey and dbkey is %s %s" %(filekey,dbkey)
print " newvalue is %s" %(newvalue)
devconfigfile, number = re.subn(filekey + ".*" + "=" + ".*",newvalue,devconfigfile)
fd=open(thisfile,'w')
fd.write(devconfigfile)
fd.close
fd = open(thisfile)
result = fd.read()
#print result
fd.close