python查找替換(二)

          python查找替換(二)
python

場景:mysql

  在特定目錄下部分配置文件中的key/value值需進行替換.正則表達式

目錄:e:\docsql

文件數:三個,分別是1.properties,2.properties,3.properties,數據庫

用於替換的值保存在mysql數據中:clb_configapp

代碼實現:ide

__author__ = 'Administrator'
fetch

#encoding: UTF-8this

import  time,MySQLdbspa

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

相關文章
相關標籤/搜索