我有一个脚本,可以将任何给定的文件夹结构转换为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)
您只有一级层次结构,因为在
all_dirs_with_dubdirs
中,您遍历目录树并将每个有效目录附加到一个平面列表result
,然后将其存储在唯一的"children"
键中。在你要做的是创建一个
使用递归可以非常优雅地完成这项工作
^{pr2}$您可以通过以下方式获得CWD的直系子女:
使用该表达式,可以编写如下递归遍历函数:
^{pr2}$然后您需要创建一个
combine_as_json()
函数,该函数将subdir结果聚合到您选择的编码/表示中。在相关问题 更多 >
编程相关推荐