#coding:utf-8 import re import glob import os def cross(strx): xCross = ''' location / { index index.php index.html; if ($http_origin ~ .*.abc.net.cn ) { add_header Access-Control-Allow-Origin $http_origin; add_header Access-Control-Allow-Credentials true; add_header Access-Control-Allow-Methods 'GET,POST'; } } ''' r = '(location / {.+?}\s*)\w' r = re.compile(r, re.DOTALL) m = r.search(strx) if m: oldX = m.group(1) strx = strx.replace(oldX, xCross) return strx def openAndSave(filePath): with open(filePath, 'r') as f: strx = f.read() strx = cross(strx) with open(filePath, 'wb') as f: f.write(strx) if __name__ == '__main__': path='D://dev' for filePath in glob.glob( os.path.join(path, u'*.conf') ): print filePath openAndSave(filePath) print '============================================'