遍历不规则的列表清单

时间:2016-12-22 06:07:06

标签: python directory-structure

我有一个包含文件夹结构的非常不规则的列表列表,我想遍历列表并检查该文件夹/子文件夹是否存在

folderStructure = [['Folder1', [subfolder1, [sub-sub-folder1, sub-sub-folder2]]], ['Folder2', [sub-folder2], [sub-folder3]], ['Folder3', [sub-folder4]], ['Folder4'], [file1, file2, file3]]

如何测试此文件夹结构是否存在?

2 个答案:

答案 0 :(得分:1)

为了实际检查文件夹是否存在,您必须指定其路径并使用os.path.exists。困难的部分是嵌套列表的字符串有时代表文件夹的名称,有时代表文件名。我编写了一个函数来测试所提供结构的成员是否存在,并尝试确定内容是否代表文件夹名称。

import os
folderStructure = [
    ['Folder1', 
        ['subfolder1', 
            ['sub-sub-folder1', 'sub-sub-folder2']
        ]
    ], 
    ['Folder2', 
        ['sub-folder2'], ['sub-folder3']
    ], 
    ['Folder3', 
        ['sub-folder4']
    ], 
    ['Folder4'], 
    ['file1', 'file2', 'file3']
]

def path_hierarchy_exists(pathslist,base_path='.'):
    print pathslist,base_path
    if isinstance(pathslist,basestring): # pathslist is a string that names a file
        return os.path.exists(os.path.join(base_path,pathslist))
    elif len(pathslist)==1: # Leaf sub-folders or leaf files
        if not path_hierarchy_exists(pathslist[0],base_path):
            return False
    elif isinstance(pathslist[0],basestring) and isinstance(pathslist[1],list):
        # pathslist is a list starting with the folder name and following with a list of folder contents
        folderName = pathslist[0]
        if not os.path.exists(os.path.join(base_path,folderName)): # Folder does not exist
            return False
        for folderContents in pathslist[1:]:
            if not path_hierarchy_exists(folderContents,os.path.join(base_path,folderName)):
                return False # Folder contents do not exist
    else: # pathslist is a list of nested folders
        for paths in pathslist:
            if not path_hierarchy_exists(paths,base_path):
                return False
    return True

print(path_hierarchy_exists(folderStructure))

答案 1 :(得分:0)

我不确定子文件夹是什么,但是如果你要查找不规则形状的数组中的字符串,这将会起作用。您应该通过阅读深度优先搜索来尝试了解这是做什么的。

folderStructure = [
    ['Folder1', 
        ['subfolder1', 
            ['sub-sub-folder1', 'sub-sub-folder2']
        ]
    ], 
    ['Folder2', 
        ['sub-folder2'], ['sub-folder3']
    ], 
    ['Folder3', 
        ['sub-folder4']
    ], 
    ['Folder4'], 
    ['file1', 'file2', 'file3']
]

def searchFolder(folder, name):
    for item in folder:
        if isinstance(item, basestring):
            if item == name:
                return True
        elif searchFolder(item, name):
            return True

    return False

print searchFolder(folderStructure, 'Folder4')

将文件夹Structure作为第一个参数并将您要搜索的文件夹的名称作为第二个参数传递。