功能更强大的操作系统。

2024-04-20 10:12:24 发布

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

因为我需要遍历目录,其中有些复杂的过滤,所以我想创建一个包装器手术室步行. 在

大概是这样的:

def fwalk(root, pred_dir, pred_files, walk_function=walk):
    """Wrapper function around the standard os.walk, that filter out
    the directories visited using a filtering predicate
    """

    for base, dirs, files in walk_function(root):
        # ignore also the root directory when not needed, which is
        # actually more important than the subdirectories
        dirs = [d for d in dirs if pred_dir(path.join(base, d))]
        files = [f for f in files if pred_files(path.join(base, f))]

        if _ignore_dirs_predicate(base) and (dirs or files):
            yield base, dirs, files

基本上它表现为手术室步行,但需要两个谓词,以便更好地组合到更高级别的函数中。 例如,这将只通过python模块:

^{pr2}$

它还需要一个walk函数,例如可以只是一个虚拟的walk,用于测试。在

def dummy_walk(_):
    test_dir = [
        ('/root/', ['d1, .git'], []),
        ('/root/d1', [], ['setup.py']),
        ('/root/test', [], ['test1.py']),
        ('/root/.git', [], [])
    ]

    # returns a function which  skips the parameter and return the iterator
    return iter(test_dir)

现在的问题是,我发现很难信任这个函数,除了使用虚拟漫游进行一些单元测试之外,很难确保它是正确的。在

有什么建议可以让它变得更好吗?在


Tags: the函数intestforbaseifdir
3条回答

您需要在适当的地方修改dir,以避免递归遍历删除的目录。使用:

dirs[:] = [d for d in dirs if pred_dir(path.join(base, d))]

这将消除对_ignore_dirs_predicate(base)的检查(并删除使用_ignore_dirs_predicate而不是{}导致的{})

您还应该重写ISA_PY以使用str.endswith()

是的。原来的界面怎么了?将谓词应用于原始输出以获得最佳结果。除了os.path.join(base, name),没有太多的改进空间。在

相关问题 更多 >