You need to enable JavaScript to run this app. 如何使用Python统计包含指定数量n个文件的文件夹总数
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python统计包含指定数量n个文件的文件夹总数

问题分析

原代码存在以下核心错误:

  • 全局累加文件计数:noOfFiles变量没有按单个文件夹重置,统计的是所有遍历过的文件总和,而非单个子文件夹内的文件数
  • 提前终止逻辑错误:匹配到符合条件的数值就直接return,只会返回当前遍历到的第几个文件夹,完全不会统计所有符合条件的文件夹总数
  • 冗余嵌套循环:两次调用os.walk,逻辑重复且执行效率低
  • 路径拼接不规范:硬编码/拼接路径,在Windows系统会报错,应该用os.path.join做跨平台兼容
正确实现

针对你使用LFW人脸数据集的场景,以下实现默认统计根目录下一级子文件夹的文件数(一级子文件夹对应单个人脸的分类目录):

import os

def count_matched_folders(root_dir, target_file_count):
    matched_count = 0
    # 遍历根目录下的所有条目
    for entry in os.scandir(root_dir):
        # 只处理文件夹
        if entry.is_dir():
            current_file_total = 0
            # 递归统计当前文件夹下的所有文件
            for _, _, files in os.walk(entry.path):
                current_file_total += len(files)
            # 匹配到目标数量就计数+1
            if current_file_total == target_file_count:
                matched_count += 1
    return matched_count

HOME_FOLDER = '/home/erfan/example/lfw/train'
print(count_matched_folders(HOME_FOLDER, 100))

如果需要统计所有层级的子文件夹,可使用以下版本:

import os

def count_all_matched_folders(root_dir, target_file_count):
    matched_count = 0
    for base, dirs, _ in os.walk(root_dir):
        for dir_name in dirs:
            dir_path = os.path.join(base, dir_name)
            current_file_total = 0
            for _, _, files in os.walk(dir_path):
                current_file_total += len(files)
            if current_file_total == target_file_count:
                matched_count += 1
    return matched_count

如果不需要统计子文件夹内的文件,仅统计当前文件夹下的直接文件,可将单个文件夹的文件统计逻辑替换为:

current_file_total = len([f for f in os.scandir(dir_path) if f.is_file()])
优化说明
  • 用os.scandir替代os.listdir遍历目录,执行效率更高,尤其适合文件数量多的场景
  • 每个文件夹单独统计文件数,统计完成后再判断是否匹配目标值,不会出现计数累加错误
  • 不需要嵌套多层文件遍历,直接取os.walk返回的files列表长度累加,减少一层循环
  • 用os.path.join拼接路径,适配Windows、Linux、macOS等不同操作系统

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 00:42:00