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

如何统计目录及所有子目录文件总数?递归函数仅统计第一层子目录

递归统计目录文件数的问题修复

你的folders_check_scan函数递归调用子目录时,没有将子目录返回的文件数累加到当前的count变量中,导致仅统计了当前目录的文件,完全忽略了子目录里的文件。

修改方法非常直接,在调用递归函数时,把返回值加到当前的count上即可:

import os
import csv

def folders_check_scan(value):
    count = 0
    for y in os.scandir(value):
        if y.is_dir():
            # 关键修改:将子目录统计的文件数累加到当前count
            count += folders_check_scan(y)
        elif y.is_file():
            count += 1
            
    return count

# 统计目录结构的函数
def list_files(startpath):
    # 获取顶层目录数量
    print(len(next(os.walk(startpath))[1]))
    print(startpath)
    
    # 用os.path.join构建路径,兼容不同操作系统
    directory_path = [os.path.join(startpath, b) for b in next(os.walk(startpath))[1]]
    
    # 遍历每个顶层目录,统计文件总数
    for x in directory_path:
        count = folders_check_scan(x)
        print(x)
        print(count)

额外优化了directory_path的生成逻辑,用os.path.join替代硬编码的\\路径分隔符,让代码在Linux、macOS等系统下也能正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 18:39:40