需求是找出文件夹里多个SQL文件里用到的所有ods开头的表有哪些
思路是先遍历每个文件,然后再用正则来匹配
代码如下:
import os
import re
# sql_regax = re.compile("WMDP_ETL_ODS.\w+|WMDP_ETL_DW.\w+",re.IGNORECASE) #需要匹配的表前缀,忽略大小写,多个条件用|分割
sql_regax = re.compile("WMDP_ETL_ODS.\w+",re.IGNORECASE)
path = 'D://Users//User//Desktop//DW' #文件夹目录
def getCurrentFile(rootDir, allFiles=[]):
list = os.listdir(rootDir) # 列出文件夹下所有的目录与文件
for i in range(0, len(list)):
path = os.path.join(rootDir, list[i])
allFiles.append(path)
return allFiles
# print("获取当前目录信息:")
currentFileList = getCurrentFile(path)
myfilelist=[]
for i in currentFileList:
file = i.split('\\')[1] #获取文件名
myfilelist.append(file)
# print(myfilelist)
for f in myfilelist:
# print(f)
# if f=='CS_BARCODE_SCAN_EVT_INC.sql':
filetxt = os.path.join(path,f)
all_the_text =open(filetxt,encoding='utf-8').read( )
res_list = sql_regax.findall(all_the_text)
if res_list!=None:
for res in res_list:
print(res+',sourece:'+f)
运行结果: