Python:使用excel文件通过shutil搜索Regex文件

kse8i1jr  于 2023-02-02  发布在  Python
关注(0)|答案(1)|浏览(109)

我有一个程序,我写的一个内部员工,需要一个CSV文件,并搜索文件服务器中列出的CSV文件,然后将每个文件复制到桌面上的文件夹。我遇到的问题与我目前的代码是,CSV必须持有确切的名称,而不是我需要正则表达式搜索这一点,并复制文件的文件名一样,在CSV中。
excel中的文件名如下所示:编号D 6957-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()

Program is able to find and copy exact file names but unable to file *like* files.
u5rb5r59

u5rb5r591#

将search_folder方法更改为如下所示:

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:
            for file_pattern in file_name:
                if file.find(file_pattern) > -1:
                    found_files.append(os.path.join(root, file))
                    shutil.copy2(file, desktop)

    return found_files

基本上,对于每个文件,我们都要迭代file_name数组来测试所有的模式。
对于测试,我们使用find方法,如果匹配,则返回找到的子字符串的位置。
也就是说,如果搜索'foo',将返回所有这些文件:

zazfoo
foobar
zazfoobar
foo

相关问题