【问题标题】:How would I rebuild a directory structure into a dictionary?如何将目录结构重建为字典?
【发布时间】:2021-12-04 03:36:33
【问题描述】:

我想采用单个文件夹路径(根目录),然后将所有文件路径放入类似于原始目录结构的字典中。

例如: 我有一个如下所示的文件夹:

root
-sub1
--someFile.txt
--someFile2.txt
-sub2
--subsub1
---veryNested.txt
--someFile3.txt
-someFile4.txt

我希望字典看起来像这样:

{'root': {
    '.dirs': {
        'sub1':{
            '.dirs':{},
            '.files':['someFile.txt', 'someFile2.txt']
        },
        'sub2':{
            '.dirs':{
                'subsub1':{
                    '.dirs':{},
                    '.files':['veryNested.txt']
                }
            },
            '.files':['someFile3.txt']
        }
    },
    '.files':['someFile4.txt']
}

我一直在环顾四周,但我真的找不到这个问题的一般性好答案。有人可以向我指出一些好的资源,或者对代码的外观进行简要和一般性的解释吗?我想在没有人 100% 牵着我的手的情况下解决这个问题,或者只是给我解决方案。如果需要更多说明,请告诉我!

【问题讨论】:

  • 我写了一个代码来解决这个问题。最好的解决方案可能涉及递归
  • "我已经写了一个代码来解决这个问题" -> 给我们看代码或者它没有发生:p

标签: python dictionary recursion directory-structure file-structure


【解决方案1】:

有很多方法可以获得目录结构的表示。

以下函数使用递归方法将您的目录结构列出到一个 json 对象中:

import os
import json

def path_to_dict(path):
    d = {'name': os.path.basename(path)}
    if os.path.isdir(path):
        d['type'] = "folder"
        d['content'] = [path_to_dict(os.path.join(path, x)) for x in os.listdir(path)]
    else:
        d['type'] = "file"
    return d
# string rapresentation 
dict_tree = json.dumps(path_to_dict('C:/Users/foo/Desktop/test'))
# convert in json
json = json.loads(dict_tree )

输出:

{'name': 'test',
 'type': 'folder',
 'content': [{'name': 'subfolder_1',
   'type': 'folder',
   'content': [{'name': 'test_file_1.txt', 'type': 'file'},
    {'name': 'test_file_2.txt', 'type': 'file'}]},
  {'name': 'subfolder_2',
   'type': 'folder',
   'content': [{'name': 'test_file_3.txt', 'type': 'file'}]}]}

EXTRA:如果您在 Linux 机器上工作,您可以使用 tree 工具获得相同的结果。为了列出特定目录的文件和子文件夹,可以通过以下命令语法指定目录名或路径:

tree -J folder_name

-J 参数用于 json 表示。

【讨论】:

  • 感谢您的帮助!我创建了自己的脚本以使输出更易于管理,但这绝对有很大帮助!
【解决方案2】:

以下代码将目录路径转换为可读字典:

感谢@BlackMath 为我指明了正确的方向!

import os
from os import path

def dirToDict(dirPath):
    d = {}
    for i in [os.path.join(dirPath, i) for i in os.listdir(dirPath) if os.path.isdir(os.path.join(dirPath, i))]:
        d[os.path.basename(i)] = dirToDict(i) # You can remove the 'basename' to get the full directory path
    d['.files'] = [i for i in os.listdir(dirPath) if os.path.isfile(os.path.join(dirPath, i))] # You can add a os.path.join(dirPath, i) here to get full file name
    return d

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 2010-11-26
    相关资源
    最近更新 更多