赞
踩
指定路径查找包含某关键字符串的文件
输出结果:
【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)
【适用于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()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。