我正在尝试为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 :(得分: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)))
(您可以根据需要插入导入,路径和保存到文件)