2016-08-24 32 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

相關問題