原本一直是有这个需求,只是之前写的是递归的方式处理,感受对资源的占用不友好,并且python的最大递归深度不超过1000,因此改了一下,这里用广度优先遍历的方式实现。
实测两层共24个文件夹,共50w的文件数量。运行时间大概3秒。如下是代码:python
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的思路函数
这里稍微改一下folder_list = list(filter(lambda bar: os.path.isdir(bar), file_folder_list))
里的的lambda
函数就能够实现判断对文件名的各类判断操做,这里函数功能的实现就彻底取决于本身的脑洞了!code
附上一个改编版: 查看包含特定后缀的文件的数量递归
import os import queue def filter_extension(filename: str, extension: str) -> bool: '''判断文件路径名的后缀是否和给定的后缀字符串相同 只是单纯的字符串判断 ''' basename_and_extension = filename.split('.') return (basename_and_extension[-1] == extension) and (len(basename_and_extension) >= 2) def get_file_quantity(folder: str, extension: str) -> int: '''BFS获取文件夹下文件的总数量''' # 判断初始文件夹 assert os.path.isdir(folder), '请输入有效的文件夹参数' assert isinstance(extension, str), '请输入有效的文件后缀名' 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)) file_list = list(filter(lambda bar: os.path.isfile(bar), file_folder_list)) match_extension_list = list(filter(lambda bar: filter_extension(bar, extension), file_list)) for folder_path in folder_list: folder_path_queue.put_nowait(folder_path) temp_file_count = len(match_extension_list) file_quantity += temp_file_count return file_quantity if __name__ == '__main__': extension = 'py' file_quantity = get_file_quantity(r'/home', extension) print(f'包含后缀 {extension } 的文件的数量: {file_quantity}')