You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python正则结合shutil实现基于Excel的文件模糊搜索复制问题

问题描述

我正在为内部员工开发一款程序,功能是读取Excel文件中的文件名,在文件服务器中搜索对应文件并复制到桌面的指定文件夹。当前代码仅支持精确文件名匹配,无法实现模糊匹配。例如Excel中的文件名为D6957-QR-1452,服务器上的对应文件名为WM_QRLabels_D6957-QR-1452_11.5x11.5_M.pdf,现有代码无法匹配到这类包含目标关键词的文件。

原代码如下:

from tkinter import filedialog, messagebox
import openpyxl
import tkinter as tk
from pathlib import Path
import shutil
import os


desktop = Path.home() / "Desktop/Comps"

tk.messagebox.showinfo("Select a directory","Select a directory" )
folder = filedialog.askdirectory()
root = tk.Tk()


root.title("Title")


lbl = tk.Label(
    root, text="Open the excel file that includes files to search for")
lbl.pack()

frame = tk.Frame(root)
frame.pack()
scrollbar = tk.Scrollbar(frame)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
listbox = tk.Listbox(frame, yscrollcommand=scrollbar.set)


def load_file():
    wb_path = filedialog.askopenfilename(filetypes=[('Excel files', '.xlsx')])
    wb = openpyxl.load_workbook(wb_path)
    global sheet
    sheet = wb.active

    listbox.pack()
    file_names = [cell.value for row in sheet.rows for cell in row]
    for file_name in file_names:
        listbox.insert('end', file_name)
    return file_names  # <--- return your list 
    
             


def search_folder(folder, file_name):
    # Create an empty list to store the found file paths
    found_files = []
    for root, dirs, files in os.walk(folder):
        for file in files:
            if file in file_name:
                found_files.append(os.path.join(root, file))
                shutil.copy2(file, desktop)

    return found_files


excelBtn = tk.Button(root, text="Open Excel File",
                     command=None)
excelBtn.pack()


zipBtn = tk.Button(root, text="Copy to Desktop",
                   command=search_folder(folder, load_file()))
zipBtn.pack()


root.mainloop()

原程序仅能找到并复制完全匹配的文件名,无法实现模糊搜索匹配。

解决方案

下面是修改后的代码,解决了模糊匹配、按钮绑定逻辑错误以及文件复制路径错误的问题:

from tkinter import filedialog, messagebox
import openpyxl
import tkinter as tk
from pathlib import Path
import shutil
import os

# 确保目标文件夹存在
desktop = Path.home() / "Desktop/Comps"
desktop.mkdir(exist_ok=True)

tk.messagebox.showinfo("Select a directory", "Select the file server directory to search")
folder = filedialog.askdirectory()
root = tk.Tk()
root.title("File Search & Copy Tool")

# 存储Excel读取的文件名列表
target_file_names = []

lbl = tk.Label(root, text="Open the Excel file containing file names to search for")
lbl.pack()

frame = tk.Frame(root)
frame.pack()
scrollbar = tk.Scrollbar(frame)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
listbox = tk.Listbox(frame, yscrollcommand=scrollbar.set)
scrollbar.config(command=listbox.yview)

def load_file():
    global target_file_names
    wb_path = filedialog.askopenfilename(filetypes=[('Excel files', '.xlsx')])
    if not wb_path:
        return
    wb = openpyxl.load_workbook(wb_path)
    sheet = wb.active
    
    listbox.delete(0, tk.END)
    target_file_names = []
    for row in sheet.rows:
        for cell in row:
            if cell.value:  # 跳过空单元格
                target_name = str(cell.value).strip()
                target_file_names.append(target_name)
                listbox.insert(tk.END, target_name)

def search_and_copy():
    if not folder:
        messagebox.showerror("Error", "Please select a search directory first")
        return
    if not target_file_names:
        messagebox.showerror("Error", "Please load an Excel file first")
        return
    
    copied_count = 0
    for target_name in target_file_names:
        if not target_name:
            continue
        # 遍历文件夹进行模糊匹配:目标关键词存在于服务器文件名中
        for root_dir, _, files in os.walk(folder):
            for file in files:
                if target_name in file:
                    source_path = os.path.join(root_dir, file)
                    dest_path = os.path.join(desktop, file)
                    try:
                        shutil.copy2(source_path, dest_path)
                        copied_count += 1
                        print(f"Copied: {source_path} -> {dest_path}")
                    except Exception as e:
                        messagebox.warning("Warning", f"Failed to copy {file}: {str(e)}")
    
    messagebox.showinfo("Complete", f"Copy finished! Total copied: {copied_count} files")

# 绑定按钮命令
excelBtn = tk.Button(root, text="Open Excel File", command=load_file)
excelBtn.pack(pady=5)

zipBtn = tk.Button(root, text="Copy to Desktop", command=search_and_copy)
zipBtn.pack(pady=5)

root.mainloop()

关键修改说明

  • 模糊匹配逻辑:将原代码中的if file in file_name改为if target_name in file,实现用Excel中的关键词去匹配服务器文件名中包含该关键词的文件。
  • 按钮绑定修复:原代码中command=search_folder(folder, load_file())会在程序启动时直接执行函数,改为绑定search_and_copy函数,点击按钮时才触发搜索复制操作。
  • 文件路径修复:shutil.copy2使用完整的源文件路径(source_path),而不是仅文件名,避免找不到文件的错误。
  • 空值处理:添加空单元格和空关键词的判断,跳过无效数据。
  • 目标文件夹初始化:使用desktop.mkdir(exist_ok=True)确保桌面的Comps文件夹存在,避免复制时因文件夹不存在报错。
  • 用户提示优化:添加错误提示和完成统计,提升用户体验。

内容的提问来源于stack exchange,提问作者SynfulAcktor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 06:35:17