Python文件夹结构和JSON的子级

2024-03-28 15:00:03 发布

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

我有一个脚本,可以将任何给定的文件夹结构转换为JSON、JSTree兼容的结构。但是,子文件夹都分组在同一级别的子文件夹下。所以文件夹中的文件夹被标记为根目录下的一个级别。如何在JSON中维护根-子-子关系?在

import os, sys, json

def all_dirs_with_subdirs(path, subdirs):

    try:
        path = os.path.abspath(path)

        result = []
        for root, dirs, files in os.walk(path):
            exclude = "Archive", "Test"
            dirs[:] = [d for d in dirs if d not in exclude]
            if all(subdir in dirs for subdir in subdirs):
                    result.append(root)
        return result

    except WindowsError:
        pass
def get_directory_listing(path):
    try:
        output = {}
        output["text"] = path.decode('latin1')
        output["type"] = "directory"
        output["children"] = all_dirs_with_subdirs("G:\TEST", ('Maps', 'Temp'))
        return output

    except WindowsError:
        pass
with open(r'G:\JSONData.json', 'w+') as f:
    listing = get_directory_listing("G:\TEST")
    json.dump(listing, f)

Tags: pathin文件夹jsonforoutputoswith
2条回答

您只有一级层次结构,因为在all_dirs_with_dubdirs中,您遍历目录树并将每个有效目录附加到一个平面列表result,然后将其存储在唯一的"children"键中。在

你要做的是创建一个

{
  'text': 'root_dir',
  'type': 'directory',
  'children': [
     {
       'text': 'subdir1 name',
       'type': 'directory',
       'children': [
         {
           'text': 'subsubdir1.1 name',
           'type': 'directory',
           'children': [
             ...
           ]
         },
         ...
       ]
     },
     {
       'text': 'subdir2 name',
       'type': 'directory',
       'children': [
         ...
       ]
     },
  ]
}

使用递归可以非常优雅地完成这项工作

^{pr2}$

您可以通过以下方式获得CWD的直系子女:

next(os.walk('.'))[1]

使用该表达式,可以编写如下递归遍历函数:

^{pr2}$

然后您需要创建一个combine_as_json()函数,该函数将subdir结果聚合到您选择的编码/表示中。在

相关问题 更多 >