Python小工具:据说这是搜索文件最快的工具!没有之一!一起感受下......

x33g5p2x  于2021-11-21 转载在 Python  
字(2.2k)|赞(0)|评价(0)|浏览(357)

电脑自带的搜索文件功能相信大家都体验过,那是真的慢,等它找到文件,我都打完一把游戏了!

那必须不能忍,于是我自己做了一个文件搜索工具,犄角旮旯的文件都能一秒钟搜索出来的那种!
保证能把你们男(女)朋友那些藏的很深的不可告人的文件分分钟找出来~

用到的环境

  1. 解释器: Python 3.8.8 | Anaconda, Inc.
  2. 编辑器: pycharm 专业版

代码展示
全部代码我都放这了,就不单独解释了,我都写在注释了。

  1. import tkinter as tk
  2. from tkinter import filedialog
  3. import os
  4. root = tk.Tk()
  5. root.geometry('600x300')
  6. root.title('学习资料搜索工具')
  7. """搜索框"""
  8. search_frame = tk.Frame(root)
  9. search_frame.pack()
  10. tk.Label(search_frame, text='关键字:').pack(side=tk.LEFT, padx=10, pady=10)
  11. key_entry = tk.Entry(search_frame) # 创建一个输入框
  12. key_entry.pack(side=tk.LEFT, padx=10, pady=10) # 将输入框显示到界面
  13. tk.Label(search_frame, text='文件类型:').pack(side=tk.LEFT, padx=10, pady=10)
  14. type_entry = tk.Entry(search_frame)
  15. type_entry.pack(side=tk.LEFT, padx=10, pady=10)
  16. button = tk.Button(search_frame, text='搜索')
  17. button.pack(side=tk.LEFT, padx=10, pady=10)
  18. list_box = tk.Listbox(root)
  19. list_box.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
  20. """点击按钮搜索文件"""
  21. def search():
  22. print('按钮被点击了')
  23. # 1. 获取关键字、文件类型
  24. key = key_entry.get()
  25. file_type = type_entry.get()
  26. print(key, file_type)
  27. # 2. 读取 windows 系统的文件
  28. dir_path = filedialog.askdirectory()
  29. print(dir_path) # 遍历文件,实现搜索功能
  30. file_list = os.walk(dir_path)
  31. for root_path, dirs, files in file_list:
  32. # 目录路径,目录下的子目录,目录下的文件
  33. # print(root_path, dirs, files)
  34. for file in files:
  35. # 过滤文件类型,搜索关键字
  36. if type_entry: # py 如果输入了类型,就进行过滤,如果没有输入,就不过滤类型
  37. if file.endswith(file_type):
  38. # 搜索关键字
  39. content = open(root_path + '/' + file, mode='r', encoding='utf-8-sig').read()
  40. if key in content:
  41. print(root_path + '/' + file)
  42. # 把结果显示到界面上
  43. list_box.insert(tk.END, root_path + '/' + file)
  44. # 3. 实现搜索功能
  45. # 4. 将搜索到的结果显示到界面
  46. # 创建滚动窗口并布局到页面上
  47. sb = tk.Scrollbar(root)
  48. sb.pack(side=tk.RIGHT, fill=tk.Y)
  49. sb.config(command=list_box.yview)
  50. list_box.config(yscrollcommand=sb.set)
  51. button.config(command=search)
  52. def list_click(event):
  53. print('列表框组件的内容被点击了')
  54. # 1. 获取到选中的内容
  55. index = list_box.curselection()[0]
  56. path = list_box.get(index)
  57. print(path)
  58. # 2. 读取选中路径的内容
  59. content = open(path, mode='r', encoding='utf-8').read()
  60. print(content)
  61. # 3. 将内容显示到新的窗口
  62. top = tk.Toplevel(root)
  63. filename = path.split('/')[-1]
  64. top.title(filename)
  65. text = tk.Text(top)
  66. text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
  67. text.insert(tk.END, content)
  68. # 绑定点击事件
  69. list_box.bind('<Double-Button-1>', list_click)
  70. root.mainloop()

这个算是比较简单的了,大家可以自行尝试一下,有什么不同的思路都欢迎在评论区发表交流。

如果看不懂的话也有相对应的视频教程→Python制作文件开发工具

如果觉得对你有帮助,记得点赞三连支持一下哈~

相关文章