簡體   English   中英

Python:使用 excel 文件使用 shutil 進行正則表達式文件搜索

[英]Python: Regex file search with shutil using an excel file

我有一個正在為內部員工編寫的程序,該程序采用 CSV 文件並在文件服務器中搜索 CSV 中列出的文件,然后將每個文件復制到桌面上的一個文件夾中。 我當前代碼遇到的問題是 CSV 必須包含確切的名稱,但我需要使用正則表達式搜索它並復制文件名與 CSV 中的文件名類似的文件。

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()


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

將您的 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方法,如果匹配,則返回找到的 substring 的 position。

也就是說,如果搜索“foo”,將返回所有這些文件:

zazfoo
foobar
zazfoobar
foo

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM