You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多目录子文件夹数量一致性校验需求及脚本完善求助

Solution to Validate Subfolder Counts Across Multiple Directories

Got it, let's build out your script to meet that validation requirement. You need to check that 5 target directories all have identical subfolder counts, with error triggers if any mismatch. Here's a complete, practical implementation:

import os

def count_subdirectories(root):
    """统计指定目录下的直接子文件夹数量(非递归)"""
    # 使用os.scandir提升性能,无需额外调用os.path.isdir
    return sum(1 for entry in os.scandir(root) if entry.is_dir())

def validate_subdir_counts(target_dirs):
    """校验所有目标目录的子文件夹数量是否一致"""
    # 先检查目录列表是否为空
    if not target_dirs:
        print("❌ Error: No target directories provided.")
        return False
    
    # 以第一个目录的子文件夹数量作为基准值
    base_count = count_subdirectories(target_dirs[0])
    print(f"ℹ️ Base subfolder count (from first directory): {base_count}")
    
    # 遍历剩余目录逐一对比
    for dir_path in target_dirs[1:]:
        # 跳过不存在的目录(可选的额外校验)
        if not os.path.isdir(dir_path):
            print(f"❌ Error: Directory '{dir_path}' does not exist or is not accessible.")
            return False
        
        current_count = count_subdirectories(dir_path)
        if current_count != base_count:
            print(f"❌ Mismatch detected! Directory '{dir_path}' has {current_count} subfolders (expected {base_count}).")
            # 这里添加你的后续错误处理逻辑:比如记录日志、发送告警、抛出异常等
            # 示例:raise ValueError(f"Subfolder count mismatch in {dir_path}")
            return False
    
    # 所有目录校验通过
    print("✅ Success: All target directories have the same number of subfolders.")
    return True

if __name__ == "__main__":
    # 替换为你的5个目标目录路径(注意Windows路径用双反斜杠或原始字符串)
    target_directories = [
        r'F:\gop\gop_img_test\2018-03-06',
        r'F:\gop\gop_img_test\2018-03-07',
        r'F:\gop\gop_img_test\2018-03-08',
        r'F:\gop\gop_img_test\2018-03-09',
        r'F:\gop\gop_img_test\2018-03-10'
    ]
    
    # 执行校验
    validation_passed = validate_subdir_counts(target_directories)
    if not validation_passed:
        # 全局错误处理流程:比如终止程序、触发告警等
        print("⚠️ Initiating error handling procedures...")
        # 示例:import sys; sys.exit(1)

Key Details Explained

  • Efficient Counting: os.scandir is used instead of os.listdir because it returns file metadata directly, making it faster to check if an entry is a directory (no extra os.path.isdir call needed).
  • Baseline Comparison: We use the first directory's subfolder count as the reference—this keeps the logic simple and avoids overcomplicating with set comparisons.
  • Robust Checks: Added a check for missing/inaccessible directories to catch edge cases before counting.
  • Extensible Error Handling: The script leaves clear spots to add your custom logic (like logging, alerts, or exceptions) when a mismatch is found.

内容的提问来源于stack exchange,提问作者user9046520

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:40:40