Python小工具:據說這是搜索文件最快的工具!沒有之一!一起感受下......


電腦自帶的搜索文件功能相信大家都體驗過,那是真的慢,等它找到文件,我都打完一把游戲了!

那必須不能忍,於是我自己做了一個文件搜索工具,犄角旮旯的文件都能一秒鍾搜索出來的那種!
保證能把你們男(女)朋友那些藏的很深的不可告人的文件分分鍾找出來~
在這里插入圖片描述
用到的環境
1. 解釋器: Python 3.8.8 | Anaconda, Inc.
2. 編輯器: pycharm 專業版

代碼展示
全部代碼我都放這了,就不單獨解釋了,我都寫在注釋了。

import tkinter as tk
from tkinter import filedialog
import os

root = tk.Tk() root.geometry('600x300') root.title('學習資料搜索工具') """搜索框""" search_frame = tk.Frame(root) search_frame.pack() tk.Label(search_frame, text='關鍵字:').pack(side=tk.LEFT, padx=10, pady=10) key_entry = tk.Entry(search_frame) # 創建一個輸入框 key_entry.pack(side=tk.LEFT, padx=10, pady=10) # 將輸入框顯示到界面 tk.Label(search_frame, text='文件類型:').pack(side=tk.LEFT, padx=10, pady=10) type_entry = tk.Entry(search_frame) type_entry.pack(side=tk.LEFT, padx=10, pady=10) button = tk.Button(search_frame, text='搜索') button.pack(side=tk.LEFT, padx=10, pady=10) list_box = tk.Listbox(root) list_box.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) """2. 點擊按鈕搜索文件""" def search(): print('按鈕被點擊了') # 1. 獲取關鍵字、文件類型 key = key_entry.get() file_type = type_entry.get() print(key, file_type) # 2. 讀取 windows 系統的文件 dir_path = filedialog.askdirectory() print(dir_path) # 遍歷文件,實現搜索功能 file_list = os.walk(dir_path) for root_path, dirs, files in file_list: # 目錄路徑,目錄下的子目錄,目錄下的文件 # print(root_path, dirs, files) for file in files: # 過濾文件類型,搜索關鍵字 if type_entry: # py 如果輸入了類型,就進行過濾,如果沒有輸入,就不過濾類型 if file.endswith(file_type): # 搜索關鍵字 content = open(root_path + '/' + file, mode='r', encoding='utf-8-sig').read() if key in content: print(root_path + '/' + file) # 把結果顯示到界面上 list_box.insert(tk.END, root_path + '/' + file) # 3. 實現搜索功能 # 4. 將搜索到的結果顯示到界面 # 創建滾動窗口並布局到頁面上 sb = tk.Scrollbar(root) sb.pack(side=tk.RIGHT, fill=tk.Y) sb.config(command=list_box.yview) list_box.config(yscrollcommand=sb.set) button.config(command=search) def list_click(event): print('列表框組件的內容被點擊了') # 1. 獲取到選中的內容 index = list_box.curselection()[0] path = list_box.get(index) print(path) # 2. 讀取選中路徑的內容 content = open(path, mode='r', encoding='utf-8').read() print(content) # 3. 將內容顯示到新的窗口 top = tk.Toplevel(root) filename = path.split('/')[-1] top.title(filename) text = tk.Text(top) text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) text.insert(tk.END, content) # 綁定點擊事件 list_box.bind('<Double-Button-1>', list_click) root.mainloop() 

這個算是比較簡單的了,大家可以自行嘗試一下,有什么不同的思路都歡迎在評論區發表交流。

如果看不懂的話也有相對應的視頻教程

如果覺得對你有幫助,記得點贊三連支持一下哈~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM