我使用这个算法从我的文件夹结构中生成MPTT:https://gist.github.com/unbracketed/946520
在github上找到,完美地满足了我的需求。目前,我有要求添加到它跳过树中的一些文件夹的功能。例如,我想跳过/tmp/A/B1/C2下的所有内容。因此,我的树将不包含来自C2 (包括C2)的任何内容。
我在python中并不是那么没用,所以我创建了查询(并将额外的列表传递给函数):
def is_subdir(path, directory):
path = os.path.realpath(path)
directory = os.path.realpath(directory)
relative = os.path.relpath(path, directory)
return not relative.startswith(os.pardir + os.sep)
/Now we can add somewhere
for single in ignorelist:
if fsprocess.is_subdir(node,single):但我的问题是,在函数中应该放在哪里?我试过在顶部这样做,如果返回,但这会退出我的整个应用程序。它在重复调用自己,所以我很迷茫。
有什么好的建议吗?我已经尝试在github上联系脚本创建者,没有所有者。这个算法做得很好,为我节省了很多时间,它非常适合我们的项目要求。
发布于 2015-09-14 19:32:37
def generate_mptt(root_dir):
"""
Given a root directory, generate a calculated MPTT
representation for the file hierarchy
"""
for root, dirs, _ in os.walk(root_dir):你的支票应该在这里:
if any(is_subdir(root, path) for path in ignorelist):
del dirs[:] # don't descend
continue就像这样。假设is_subdir(root, path)返回True,如果root是path的子目录。
dirs.sort()
tree[root] = dirs
preorder_tree(root_dir, tree[root_dir])
mptt_list.sort(key=lambda x: x.left)https://stackoverflow.com/questions/32560495
复制相似问题