当前位置:   article > 正文

【Python | 批量查找当前路径下包含某关键字的文件】_python查找包含关键词的文件

python查找包含关键词的文件

指定路径查找包含某关键字符串的文件
输出结果:
在这里插入图片描述

【Excel中关键字查找】

import os,sys,stat,xlrd
import time
#from numba import autojit
#from numba import jit
#@jit

"""
指定文件路径查找Excel中是否包含某些字符串
"""
#@autojit

def WritePath(content):
    """
    写入Log文件
    """
    path=r'C:\\Users\\QXZ2MDO\\Desktop\\DWH+文档\\DWH文档\\数据字典\\TEMP\\FindResults.txt'
    with open(path, 'a') as f:  # 设置文件对象
        f.write(content)
        f.write('\n')#实现换行的功能
        print(content)
        
def Find_Keywords_Excel(path,select):
    ls = os.listdir(path)
    for i in ls:
        c_path = os.path.join(path, i)
        if os.path.isdir(c_path):
            Find_Keywords_Excel(c_path)
        elif os.path.splitext(c_path)[1] == '.xlsx' and r"~$" not in r''+c_path:
            workbook  = xlrd.open_workbook(c_path) 
            worksheets = workbook.sheet_names()
            for sheet in worksheets:
                count = 0
                worksheet1 = workbook.sheet_by_name(u''+sheet)
                num_rows = worksheet1.nrows
                num_cols = worksheet1.ncols
                for rown in range(num_rows):
                    for coln in range(num_cols):
                        cell = worksheet1.cell_value(rown,coln)
                        if select in str(cell):
                            #print(c_path)
                            WritePath(c_path)
                            count += 1
                            break
                    if count > 0:
                        break
                if  count > 0:
                    break 
                    
def Find_Keywords_Excel_Mian(select_list,path):
    for select in select_list:
        #print("关键字:"+select)
        WritePath("关键字:"+select)
        Find_Keywords_Excel(path,select)

def file_name_walk(file_dir):
    #读取指定目录下的文件名
    # root   当前目录路径
    # dirs   当前路径下所有子目录
    # files  当前路径下所有非目录子文件
    FileList=[]
    for root, dirs, files in os.walk(file_dir):
        for i in dirs:
            FileList.append(""+root+"\\"+i) 
    return FileList


def defmain(path,select_list):
    Start_Time = time.time()
    file_name_walk(path)
    for i in file_name_walk(path):
        WritePath("路径:{Path}".format(Path=i))
        Find_Keywords_Excel_Mian(select_list,i)
    End_Time = time.time() 
    WritePath("执行时间:{Time}s".format(Time=End_Time-Start_Time))
    
path        =  r"C:\Users\QXZ2MDO\Desktop\DWH+文档\DWH文档\数据字典\TEMP"
select_list =  "收入"
defmain(path,select_list)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79

【适用于txt、sql】

import os 
import time
import win32com.client as win32 

flag = 0

# 读取txt文件
Log_path_file_path=r"./Find_String_Configuration.txt"
path_file = open(Log_path_file_path, 'r', encoding='utf-8')
# 按行读取
line = path_file.readlines()
# 对两行内容去除换行符,去除引号
path      = line[3].split('=')[1].strip('\n').replace("'", "")
path_log  = line[4].split('=')[1].strip('\n').replace("'", "")
text_List = line[5].split('=')[1].strip('\n').replace("'", "")
text_List  = text_List.split(',')
    
def truncateText():
    Log_path=path_log+"\\Search_Result_List.txt"
    with open(Log_path,'a+',encoding='utf-8') as LogText:
        LogText.truncate(0)
    
def WritePath(content):
    """
    追加写入Log List具体内容
    """
    Log_path=path_log+"\\Search_Result_List.txt"
    f = open(Log_path,mode='a+')
    f.write('{time} {content}\n'.format(time=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())),content=content))
    f.close()  
    #print(content)

def WritePathTitle(keywords):
    """
    覆盖写入Log文件时间标题
    """
    Log_path=path_log+"\\Search_Result_List.txt"
    f = open(Log_path,mode='a+')
    f.write('\n查找日期:{Date}\n当前关键字【{keywords}】包含列表:\n'.format(Date=time.strftime('%Y-%m-%d'),keywords=keywords))
    f.close()
    
def walk(path):
    """
    搜索文件的绝对路径 
    """
    path_List=[]
    if not os.path.exists(path):
        return -1
    for root,dirs,names in os.walk(path):
        for filename in names:
            path_Str=os.path.join(root,filename) #路径和文件名连接构成完整路径
            path_List.append(path_Str)
    return path_List
        
def getfiles(path,text):
    """
    查找关键字文件
    """
    # 将flag设置全局变量,防止递归查找时信息提示错误。
    global flag
    for abs_path in walk(path):
        if os.path.isfile(abs_path):
            f = open(abs_path, "r",encoding="utf-8")
            # 在文件中找到要查到的字符串后进行打印,并将flag置为1
            if text.upper() in f.read().upper():
                flag = 1
                WritePath(abs_path)
    if flag == 0:
        WritePath("该关键字【{text}】没有找到!\n".format(text=text)) 
        return False
    return True

def send_mail(): 
    """
    邮件发送
    """
    # 读取txt文件
    Log_path_file_path=path_log+"\\Find_String_Configuration.txt"
    path_file = open(Log_path_file_path, 'r', encoding='utf-8')
    # 按行读取
    line = path_file.readlines()
    # 对两行内容去除换行符,去除引号
    send_account    = line[0].split('=')[1].strip('\n').replace("'", "")
    To_account      = line[1].split('=')[1].strip('\n').replace("'", "")
    CC_account      = line[2].split('=')[1].strip('\n').replace("'", "")
   
    outlook_app = win32.Dispatch('Outlook.Application')
 
    mail_item = outlook_app.CreateItem(0)   # 0: olMailItem
    mail_item.To = To_account#收件人
    mail_item.CC = CC_account#抄
        
    mail_item.Recipients.Add(send_account)
    mail_item.Subject = 'keyword search :{0}'.format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) )
    Log_path=path_log+"\\Search_Result_List.txt"
    mail_item.Attachments.Add(Log_path) # 添加正常的附件
    
    
    mail_item.BodyFormat = 2   # 2: Html format
    mail_item.HTMLBody =''' 
            <br>Dear All,</br> 
            <br></br> 
            <br>搜索关键字List:\n{Search_Result_List}</br>   
            <br></br> 
            <br>查找结果请查看附件,谢谢!</br>   
            <br></br> 
            <br>Regards</br> 
            '''.format(Search_Result_List=str(text_List))

    mail_item.Send()
    
def startDef(text_List,path):
    """
    开始执行
    """
    for text in text_List:
        print(str(text))
        WritePathTitle(text)        
        getfiles(path,text)
    print("end..")



truncateText()        
startDef(text_List,path)
#send_mail()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/319474
推荐阅读
相关标签
  

闽ICP备14008679号