Python文件内容搜索工具

Python文件内容搜索工具_第1张图片

#头文件
import tkinter as tk
from tkinter import filedialog,colorchooser,messagebox
import os

def select_file():
    print("点击搜索")
    #获取关键字和文件类型
    keyword = keyword_entry.get()
    if not keyword:
        messagebox.showinfo(message="关键字")
        return
    file_type = type_entry.get()
    if not type_entry:
        messagebox.showinfo(message="文件类型")
        return

    #获取文件夹路径
    filepath=filedialog.askdirectory()
    print("要搜索的路径为:{},关键字:{},文件类型:{}".format(filepath,keyword,filepath))

    #遍历并过滤文件夹,文件插入到列表中
    result_list_box.delete(0, tk.END)#插入前清空列表
    for dir_path,dir_name,filenames in os.walk(filepath):#文件夹路径 路径名 文件夹下的文件名
        for filename in filenames:
            _file = os.path.join(dir_path.replace('/','\\'),filename)
            if file_type and not _file.endswith(file_type):
                continue
                if keyword:
                    with open(_file,'r',encoding='utf-8') as f:
                        if keyword not in f.read():
                            continue
                result_list_box.insert(tk.END,_file)
    print("end")


root = tk.Tk()
root.geometry("600x300")
root.title("everytjing")
root.iconbitmap("./speed.ico")

# 搜索区域
search_frame = tk.Frame()
search_frame.pack()

# 关键字和文件类型
tk.Label(search_frame, text="关键字:").pack(side=tk.LEFT, padx=10)
keyword_entry = tk.Entry(search_frame)
keyword_entry.pack(side=tk.LEFT, padx=10)

tk.Label(search_frame, text="文件类型:").pack(side=tk.LEFT, padx=10)
type_entry = tk.Entry(search_frame)
type_entry.pack(side=tk.LEFT, padx=10)

# 搜索按钮
search_button = tk.Button(search_frame, text="搜索",command = select_file)
search_button.pack(side=tk.LEFT, padx=10)

search_listbox = tk.Listbox(root)
search_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

sb1 = tk.Scrollbar(root, command=search_listbox.yview)
sb1.pack(side=tk.RIGHT, fill=tk.Y)
search_listbox.config(yscrollcommand=sb1.set)

result_list_box = tk.Listbox(root)
result_list_box.pack(fill=tk.BOTH,expand=True)

root.mainloop()

你可能感兴趣的:(Python,python)