python-统计指定文件夹下所有的文件数量BFS方式

19次阅读

共计 890 个字符,预计需要花费 3 分钟才能阅读完成。

python 统计指定文件夹下所有的文件数量

本来一直是由这个需求,只是以前写的是递归的方式处理,感觉对资源的占用不友好,而且 python 的最大递归深度不超过 1000,所以改了一下,这里用广度优先遍历的方式实现。
实测两层共 24 个文件夹,共 50w 的文件数量。运行时间大概 3 秒。以下是代码:

import os
import queue

def get_file_quantity(folder: str) -> int:
    '''BFS 获取文件夹下文件的总数量'''
    # 判断初始文件夹
    assert os.path.isdir(folder), '请输入有效的文件夹参数'
    file_quantity = 0                       # 初始化文件数量
    folder_path_queue = queue.Queue()
    folder_path_queue.put_nowait(folder)    # 初始化队列的值
    # 处理队列里的文件夹
    while not folder_path_queue.empty():
        folder = folder_path_queue.get_nowait()
        file_folder_list = list(map(lambda bar: os.path.join(folder, bar), os.listdir(folder)))
        folder_list = list(filter(lambda bar: os.path.isdir(bar), file_folder_list))
        for folder_path in folder_list:
            folder_path_queue.put_nowait(folder_path)
        temp_file_count = len(file_folder_list) - len(folder_list)
        file_quantity += temp_file_count
    return file_quantity
    
if __name__ == '__main__':
    file_quantity = get_file_quantity(r'/home')
    print(f'文件总数是: {file_quantity}')

思路

这里主要是使用了队列,就是普通的 BFS 的思路

正文完
 0