Python 将文件夹列表和完整路径导出为 JSTree JSON

Python export list of folders & full path as JSON for JSTree

我正在尝试为 jstree 创建一个 JSON 文件。但是我无法让这段代码输出文件夹的完整路径并且只显示文件夹。我是 Python 的新手,如果有任何见解,我将不胜感激!

目标是让用户 select 一个文件夹,并在 JSTree 中恢复该文件夹的完整路径。 (不在此代码中)。

import os
import json

def path_to_dict(path):
    d = {'text': os.path.basename(path)}
    if os.path.isdir(path):
                d['type'] = "directory"
                for root, directories, filenames in os.walk('U:\PROJECTS\MXD_to_PDF'):
                    for directory in directories:
                        d['path']= os.path.join(root, directory)
                d['children'] = [path_to_dict(os.path.join(path,x)) for x in os.listdir\

        (path)]
    else:
        d['type'] = "file"
        #del d["type"]

    return d

print json.dumps(path_to_dict('U:\PROJECTS\MXD_to_PDF\TEST'))

with open('U:\PROJECTS\MXD_to_PDF\TEST\JSONData.json', 'w') as f:
     json.dump(path_to_dict('U:\PROJECTS\MXD_to_PDF\TEST'), f)

输出:

{
"text": "TEST"
, "type": "directory"
, "children": [{
    "text": "JSONData.json"
    , "type": "file"
}, {
    "text": "Maps"
    , "type": "directory"
    , "children": [{
        "text": "MAY24MODIFIED.mxd"
        , "type": "file"
    }, {
        "text": "MAY24MODIFIED 2016-05-24 16.16.16.pdf"
        , "type": "file"
    }, {
        "text": "testst"
        , "type": "directory"
        , "children": []
        , "path": "U:\PROJECTS\MXD_to_PDF\TEST2\Maps\exported"
    }]
    , "path": "U:\PROJECTS\MXD_to_PDF\TEST2\Maps\exported"
}]
, "path": "U:\PROJECTS\MXD_to_PDF\TEST2\Maps\exported"

}

对我来说,以下解决方案有效:(您只需要目录)

def get_list_of_dirs(path):
    output_dictonary = {}
    list_of_dirs = [os.path.join(path, item) for item in os.listdir(path) if os.path.isdir(os.path.join(path, item))]
    output_dictonary["text"] = path
    output_dictonary["type"] = "directory"

    output_dictonary["children"] = []

    for dir in list_of_dirs:
        output_dictonary["children"].append(get_list_of_dirs(dir))
    return output_dictonary

print(json.dumps(get_list_of_dirs(path)))

(您可以根据需要插入导入、路径和保存到文件)