不规则列表

2024-10-02 02:24:23 发布

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

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

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

如何测试此文件夹结构是否存在?你知道吗


Tags: 文件夹列表结构file1file2subfolder1folder2folder1
2条回答

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

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')

将文件夹结构作为第一个参数传递,将要搜索的文件夹的名称作为第二个参数传递。你知道吗

为了实际检查文件夹是否存在,必须指定其路径并使用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))

相关问题 更多 >

    热门问题