Python正则取目录下文件中SQL语句包含的数据表名

替换目录为自己的目录即可:

import os
import re
 
newPath = []
 
filename = r'C:\Users\用户\Desktop\测试\check_name.txt'
with open(filename, 'w',encoding="utf-8") as file_object:
    file_object.write("cpt tablelist\n")
 
def findAllFile(base):
    for root, ds, fs in os.walk(base):
        for f in fs:
            fullname = os.path.join(root, f)
            yield newPath.append(fullname)
 
def main():
    base = r'C:\Users\用户\Desktop\测试'
    for i in findAllFile(base):
        #print(i)
        pass
 
if __name__ == '__main__':
    main()
 
for p in newPath:
     
    with open(p,"r",encoding="utf-8") as fi:
        m = fi.read()
        pat1 = re.compile("from\s+" + '([^\s\(]\S+?)[ \n\)\]\"\']',re.I)
        pat2 = re.compile("join\s+" + '([^\s\(]\S+?)[ \n\)\]\"\']',re.I)
        result1 = pat1.findall(m)
        result2 = pat2.findall(m)
        newlines = p+":"+str(list(set([x.strip().upper() for x in result1]+[x.strip().upper() for x in result2])))+'\n'
    print(newlines)
    with open(filename, 'a') as file_object:
        file_object.write(newlines)
posted @ 2021-08-11 15:37  灯熄帘摇月候身  阅读(193)  评论(0编辑  收藏  举报