2016-08-24 137 views
0

我想为jstree创建一个JSON文件。但是,我无法获得此代码来输出文件夹的完整路径,只显示文件夹。我是Python的新手,希望有任何见解!Python导出JSON文件夹和完整路径的列表

目标是让用户选择一个文件夹并将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" 

}

回答

0

对我来说,下面的解决方案工作:(你想只目录)

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))) 

(您可以将进口,你的路径,并保存到你想要的文件)

+0

太棒了。谢谢。我必须弄清楚你是怎么做到的! – Infinity8

+0

反正有没有双反斜杠? “U:\\ PROJECTS \\ MXD_to_PDF \\ TEST2”我看到我们可以添加codecs.escape_decode但不知道该放置在哪里? – Infinity8

+0

这是plattform特有的,在windows上你有类似你写的东西。我在那看到两个选项: 1.你可以用'os.sep'来玩,用你想要的东西代替它(https://docs.python.org/2/library/os.html) 2.由于在你可以使用'd [“text”]。replace(“\\”,“\”)' – phev8