python 递归查找统计某个文件夹下的文件数量[转]

python 递归查找统计某个文件夹下的文件数量[转]

link: https://blog.csdn.net/fscanf_fread/article/details/106154227

操作系统下的文件夹具有递归属性,主文件夹可以包含子文件和子文件夹,每个子文件夹下又可以包含更多的文件和文件夹, 当我们想要统计当前文件夹下所有的文件数量时,用递归的方法可以容易的实现。

 

用tree /f /a命令查看一下文件夹的目录结构

C:\TEST

| test1.txt

| test2.txt

| test3.txt

|

\---sub_test

test4.txt

test5.txt

 

python 代码实现

import os

 

def countFiles(root_path):

    assert os.path.exists(root_path)

    total_files = 0

    item_list = os.listdir(root_path)

    if len(item_list) == 0:

        return 0

    for item in item_list:

        next_path = os.path.join(root_path, item)

        if os.path.isfile(next_path):

            total_files += 1

        else:

            total_files += countFiles(next_path)

 

    return total_files

 

 

if __name__ == '__main__':

    root_path = 'C:\\test'

    num = countFiles(root_path)

    print(f'total files: {num}')

 

  • 输出结果

total files: 5

原文地址:https://www.cnblogs.com/xiexiaokui/p/15532990.html