2016-08-24 29 views
0

jstree用のJSONファイルを作成しようとしています。しかし、私はこのコードがフォルダのフルパスを出力し、フォルダのみを表示することに問題があります。私はPythonには新しく、どんな洞察力にも感謝します!JSTreeのJSONとしてのフォルダとフルパスのPythonエクスポートリスト

目的は、ユーザーにフォルダを選択させ、そのフォルダの完全パスを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特有のもので、あなたが書いたようなものを持っています。 2つのオプションがあります: 1. 'os.sep'で遊んで、好きなものに置き換えることができます(https://docs.python.org/2/library/os.html) 2.パスは単なる文字列です。 'd [" text "]。replace(" \\ "、" \ ")' – phev8

関連する問題