如何从文件路径获取文件字典 (python)

How to get dictionary of files from file path (python)

我正在尝试从文件路径列表中获取字典。我找到了其他方法,但没有深入研究。我用过代码:

# fs is a list of files
directories = {'': set()}

for f in fs:
    splitted = f.split("\")
    directories[''].add(splitted[0])

    for i in range(len(splitted)):
        if i == len(splitted)-1:
            break

        d = ''
        for j in splitted[0:i+1]:
            d += j + os.path.sep

        d = d[0:-1]

        if not d in directories:
            directories[d] = set()

        directories[d].add(splitted[i+1])

fs 是:

['C:\aydin-os\filesystem\', 'C:\aydin-os\filesystem\apps', 'C:\aydin-os\filesystem\apps\aydin-browse', 'C:\aydin-os\filesystem\apps\aydin-browse\main.app', 'C:\aydin-os\filesystem\apps\calculator', 'C:\aydin-os\filesystem\apps\calculator\main.app', 'C:\aydin-os\filesystem\system', 'C:\aydin-os\filesystem\system\apps', 'C:\aydin-os\filesystem\system\apps\apps.stats', 
'C:\aydin-os\filesystem\system\data', 'C:\aydin-os\filesystem\system\data\data.stats', 'C:\aydin-os\filesystem\users', 'C:\aydin-os\filesystem\users\aydin', 'C:\aydin-os\filesystem\users\aydin\data', 'C:\aydin-os\filesystem\users\aydin\data\password.stats']

目录是:

{'': {'C:'}, 'C:': {'aydin-os'}, 'C:\aydin-os': {'filesystem'}, 'C:\aydin-os\filesystem': {'', 'apps', 'users', 'system'}, 'C:\aydin-os\filesystem\apps': {'aydin-browse', 'calculator'}, 'C:\aydin-os\filesystem\apps\aydin-browse': {'main.app'}, 'C:\aydin-os\filesystem\apps\calculator': {'main.app'}, 'C:\aydin-os\filesystem\system': {'data', 'apps'}, 'C:\aydin-os\filesystem\system\apps': {'apps.stats'}, 'C:\aydin-os\filesystem\system\data': {'data.stats'}, 'C:\aydin-os\filesystem\users': {'aydin'}, 'C:\aydin-os\filesystem\users\aydin': {'data'}, 'C:\aydin-os\filesystem\users\aydin\data': {'password.stats'}}

我发现使用 defaultdict 可以嵌套文件路径。任何感兴趣的人的代码:

# fs is the list of the files
for idx in range(len(fs)):
    fs[idx] = fs[idx].replace('\','/').replace('C:/aydin-os/','')

for f in fs:
    f2 = f.split('/')
    estring = 'files'
    for f3 in f2:
        if f3 == '':
            continue
        estring += '["' + f3 + '"]'
    estring += ' = {}'
    exec(estring)