52 lines
1.5 KiB
Python
52 lines
1.5 KiB
Python
import os
|
|
import random
|
|
|
|
|
|
def get_random_file_from_dir(directory):
|
|
image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp'}
|
|
image_files = []
|
|
|
|
if not os.path.exists(directory):
|
|
print(f"Error: Directory '{directory}' does not exist.")
|
|
return None
|
|
|
|
if not os.access(directory, os.R_OK):
|
|
print(f"Error: No read access to directory '{directory}'.")
|
|
return None
|
|
|
|
print(f"Scanning directory: {directory} (including subdirectories)")
|
|
|
|
# 使用 os.walk() 递归遍历所有子目录
|
|
for root, _, files in os.walk(directory):
|
|
for file in files:
|
|
_, ext = os.path.splitext(file)
|
|
if ext.lower() in image_extensions:
|
|
full_path = os.path.join(root, file)
|
|
image_files.append(full_path)
|
|
|
|
if not image_files:
|
|
print("No image files found in the directory (including subdirectories).")
|
|
return None
|
|
|
|
return random.choice(image_files)
|
|
|
|
|
|
def get_xiuren_pic():
|
|
# 使用示例
|
|
directory = 'xiuren' # 替换为你的目录路径
|
|
random_file_path = get_random_file_from_dir(directory)
|
|
if random_file_path:
|
|
return os.path.abspath(random_file_path)
|
|
else:
|
|
return None
|
|
|
|
|
|
def get_xiuren_heisi_pic():
|
|
# 使用示例
|
|
directory = 'xiuren/heisi' # 替换为你的目录路径
|
|
random_file_path = get_random_file_from_dir(directory)
|
|
if random_file_path:
|
|
return os.path.abspath(random_file_path)
|
|
else:
|
|
return None
|