Python多线程模板,读取文件夹所有文件,根据需求自行更改
from queue import Queue import threading import os import openpyxl from Levenshtein import distance # 提高匹配速度 #import difflib # 关键字模糊匹配度 from datetime import datetime import time # 定义线程数和队列 num_threads = 4 file_queue = Queue() # 定义序号 count_lock = threading.Lock() count = 0 # 定义要遍历的文件夹路径 # folder_path = "C:\files\" # 测试 folder_path = input("输入文件路径,如:\033[38;2;10;10;255mC:\files\033[0m\n") # 遍历文件夹并将文件名加入队列 for filename in os.listdir(folder_path): file_queue.put(os.path.join(folder_path, filename)) current_path = os.getcwd() # 获取当前路径用来保存文件 def _file_count(filePath): #此处填写要使用多线程执行的代码 pass def process_file(): '''定义线程函数''' global count while True: file_path = file_queue.get() try: # 使用锁来保护它,以确保每个线程都能正确地更新计数器 with count_lock: count += 1 file_number = count # 调用自定义函数 _file_count(file_path) except Exception as e: print(f"{file_number}--log,,\033[31m文件读取错误\033[0m: {file_path}") print(f'原因:\033[36m{e}\033[0m') with count_lock: count -= 1 # 出错时回退计数器 continue finally: file_queue.task_done() def num_RorN(value, n): '''数字取n位小数''' if isinstance(value, (int, float)): return round(value, n) # 创建线程并运行 start = time.time() # 开始运行时间 for i in range(num_threads): t = threading.Thread(target=process_file) t.daemon = True t.start() # 等待队列中的所有任务完成 file_queue.join() end = time.time()# 结束运行的时间 运行时间 = end-start input(f'已完成,耗时:\033[32m{int(运行时间/60)}分钟({num_RorN(运行时间,2)}秒)\033[0m,任意键退出')