From 48f7426937693711aa65f67a8ef8326478278dfc Mon Sep 17 00:00:00 2001 From: liuwei Date: Thu, 6 Mar 2025 17:57:58 +0800 Subject: [PATCH] =?UTF-8?q?=E7=A7=80=E4=BA=BA=E7=BD=91=E5=9B=BE=E7=89=87?= =?UTF-8?q?=E9=9A=8F=E6=9C=BA=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- xiuren/random_pic.py | 23 ++++++++--------------- 1 file changed, 8 insertions(+), 15 deletions(-) diff --git a/xiuren/random_pic.py b/xiuren/random_pic.py index e1d0344..822b99c 100644 --- a/xiuren/random_pic.py +++ b/xiuren/random_pic.py @@ -3,24 +3,17 @@ import random def get_random_file_from_dir(directory): - selected_file = None - file_count = 0 - # 定义图片文件的扩展名列表 image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp'} + image_files = [] - # 遍历目录及其所有子目录 - for root, dirs, files in os.walk(directory): - for file in files: - # 获取文件扩展名 - _, ext = os.path.splitext(file) - # 只考虑图片文件 - if ext.lower() in image_extensions: - file_count += 1 - if random.randint(1, file_count) == 1: - # 每个图片文件有1/file_count的概率被选中 - selected_file = os.path.join(root, file) + with os.scandir(directory) as entries: + for entry in entries: + if entry.is_file(): + _, ext = os.path.splitext(entry.name) + if ext.lower() in image_extensions: + image_files.append(entry.path) - return selected_file + return random.choice(image_files) if image_files else None def get_xiuren_pic():