[Python急救站]

发布时间 2023-12-11 12:34:15作者: Jinylin

对于一个程序员,有时候文件太多,忘记放哪里了,那有没有一个可以帮你定位到文件的文件管理工具呢,抱着这样的想法,我做了以下这个代码,可以快速定位找到文件所在位置。

import os
import tkinter as tk
import time
import subprocess


# 函数用于搜索文件
def search_files():
    file_name = entry.get()  # 从输入框获取文件名

    start_time = time.time()  # 开始计时

    found_files = []  # 存储找到的文件的列表
    for drive in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":  # 遍历所有可能的盘符
        drive_path = drive + ":\\"
        for root, dirs, files in os.walk(drive_path):  # 遍历目录树
            for file in files:  # 遍历当前目录中的所有文件
                if file_name.lower() in file.lower():  # 检查文件名是否与搜索查询匹配
                    found_files.append((os.path.abspath(os.path.join(root, file)), file))  # 将文件添加到列表中
            for i in dirs:  # 遍历当前目录中的所有子目录
                if file_name.lower() in i.lower():  # 检查目录名是否与搜索查询匹配
                    found_files.append((os.path.abspath(os.path.join(root, i)), i))  # 将目录添加到列表中

    end_time = time.time()  # 停止计时
    elapsed_time = end_time - start_time  # 计算经过的时间

    result_text.delete(1.0, tk.END)  # 清空结果文本框
    if len(found_files) > 0:  # 如果找到了文件
        result_text.insert(tk.END, f"找到以下文件或文件夹匹配文件名 '{file_name}':\n")
        for i, (path, name) in enumerate(found_files):  # 遍历找到的文件
            result_text.insert(tk.END, f"{path} {name}\n")  # 显示文件路径和名称
        open_button.config(state=tk.NORMAL)  # 启用“打开文件夹”按钮
    else:  # 如果未找到文件
        result_text.insert(tk.END, f"未找到匹配文件名 '{file_name}' 的文件或文件夹。")
        open_button.config(state=tk.DISABLED)  # 禁用“打开文件夹”按钮

    result_text.insert(tk.END, f"搜索耗时: {elapsed_time:.2f} 秒")  # 显示经过的时间


# 函数用于打开选定的目录
def open_directory():
    selected_file = result_text.get("sel.first", "sel.last")  # 从结果文本框中获取选定的文件
    if selected_file:
        subprocess.Popen(f'explorer /select,"{selected_file}"', shell=True)  # 打开包含文件的目录


window = tk.Tk()
window.title("文件管理工具")

# 获取屏幕宽度和高度
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()

# 计算窗口位置和大小
window_width = screen_width * 2 // 3
window_height = screen_height * 2 // 3
window_x = (screen_width - window_width) // 2
window_y = (screen_height - window_height) // 2

# 设置窗口位置和大小
window.geometry(f"{window_width}x{window_height}+{window_x}+{window_y}")

search_frame = tk.Frame(window)
search_frame.pack()

label = tk.Label(search_frame, text="请输入要搜索的文件名:")
label.pack(side=tk.LEFT)
entry = tk.Entry(search_frame)
entry.pack(side=tk.LEFT)

button_frame = tk.Frame(window)
button_frame.pack()

search_button = tk.Button(button_frame, text="搜索", command=search_files)
search_button.pack(side=tk.LEFT)

open_button = tk.Button(button_frame, text="打开文件夹", command=open_directory, state=tk.DISABLED)
open_button.pack(side=tk.LEFT)

result_frame = tk.Frame(window)
result_frame.pack(fill=tk.BOTH, expand=True)

scrollbar = tk.Scrollbar(result_frame)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

result_text = tk.Text(result_frame, selectbackground="lightblue", yscrollcommand=scrollbar.set)
result_text.pack(fill=tk.BOTH, expand=True)

scrollbar.config(command=result_text.yview)

result_text.tag_configure("sel", background="lightblue")

window.mainloop()

程序运行结果如下:

单击目录选择打开,即可打开文件所在位置。

好了赶紧去试试吧!