#coding=utf-8 import sys,os,re,chardet,getopt repattern = re.compile(r'.*[\.]{1}([^\.]+)') zonekey = re.compile(r'zone:\s+([\S]+)[^\r\n]*') dbindexkey = re.compile(r'dbindex:\s+([\S]+)[^\r\n]*') #re.compile(r'\s+([\S]+)\s*;') #获取路径下的指定类型文件列表 def getFileList(path, fileList): for parent, dirnames, filenames in os.walk(path): for filename in filenames: match = repattern.match(filename) if match: filetype = match.groups()[0] if filetype in ['yaml']: fileList.append(os.path.join(parent, filename)) if __name__ == '__main__': zoneid = 0 dbindex = 0 try: opts,args = getopt.getopt(sys.argv[1:], "hp:z:d:", ["help","zone","dbindex"]) for opt, arg in opts: if opt in ("-z", "--zone"): zoneid = arg if opt in ("-d", "--dbindex"): dbindex = arg except getopt.GetoptError: useage() sys.exit(1) print(zoneid) print(dbindex) fileList = [] yamlFile = './' getFileList(yamlFile, fileList) for filePath in fileList: lines = [] file = open(filePath, 'r', encoding='utf-8') #file = open(filePath, 'r') if file: print('file done:',filePath) for line in file.readlines(): #line = line.strip() match = zonekey.search(line) if match and zoneid != 0 and zoneid != '0': line = ' zone: ' + str(zoneid) + '\n' match = dbindexkey.search(line) if match and dbindex != 0 and dbindex != '0': line = ' dbindex: ' + str(dbindex) + '\n' lines.append(line) file.close() if len(lines) > 0: file = open(filePath, 'w', encoding='utf-8') #file = open(filePath, 'w') if file: file.writelines(lines) file.close()