python多处理中深度优先搜索的优化

2024-06-28 16:09:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个目录,我使用下面的函数递归遍历它。你知道吗

for _item in _depth_first_traverse(start_folder):
    yield _item

def _depth_first_traverse(folderobj):
    #listcontents is method of folderobj class which return folder or file obj at immediate first level
    for _item in folderobj.listContents():
        yield _item
        # If the item is folder do recursive listing inside that folder
        if _item.isFolder:
            try:
                for _depth_item in _depth_first_traverse(_item):
                    yield _depth_item
            except Exception as e:
                pass
    return

上面的函数工作正常,并生成文件或文件夹对象。但是,当目录包含大量文件和文件夹时,计算速度非常慢。你知道吗

因此,我想重构代码,要么使用多处理模块并行地执行每个文件夹的递归列表,要么生成一个文件夹。需要知道如何实现这个或任何其他解决方案,使这个块执行快是欢迎的。你知道吗


Tags: 函数in目录文件夹forreturnisfolder