如何将文件路径转换为Treeview? [英] How to convert a file path into treeview?

查看:90
本文介绍了如何将文件路径转换为Treeview?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我在python中有一些文件,它们具有以下文件路径格式:

Right now I have a few files in python that have following file path format:

a/b/c/d/e/file1
a/b/c/d/e/file2
a/f/g/h/i/file3
a/f/g/h/i/file4

现在,当我在Python中获取这些路径时,我想将其转换为第三方jquery插件(例如fancytree,jqxTree)可以读取的JSON格式,以将其转换为树视图.也许还有其他更简单的方法可以做到这一点,请提出建议.谢谢!

Now, when I fetch these paths in Python, I want to turn this into a JSON format that a third party jquery plugin (e.g. fancytree, jqxTree) can read in order to convert it into a treeview. Maybe there are other easier ways to do it, please suggest. Thanks!

推荐答案

从Python中,您可以按以下方式生成所需的JSON(请注意,如果您只是在跨JSON运送JSON,则不需要缩进和排序行,但它们使输出可读以进行调试):

From Python, you can generate the JSON you want as follows (note that the indent and sort aren't necessary if you're just shipping the JSON across the line, but they make the output readable for debugging):

import collections
import json

myfiles = '''
    a/b/c/d/e/file1
    a/b/c/d/e/file2
    a/f/g/h/i/file3
    a/f/g/h/i/file4
'''

# Convert to a list
myfiles = myfiles.split()


def recursive_dict():
    """
    This function returns a defaultdict() object
    that will always return new defaultdict() objects
    as the values for any non-existent dict keys.
    Those new defaultdict() objects will likewise
    return new defaultdict() objects as the values
    for non-existent keys, ad infinitum.
    """
    return collections.defaultdict(recursive_dict)


def insert_file(mydict, fname):
    for part in fname.split('/'):
        mydict = mydict[part]

    # If you want to record that this was a terminal,
    # you can do something like this, too:
    # mydict[None] = True

topdict = recursive_dict()
for fname in myfiles:
    insert_file(topdict, fname)

print(json.dumps(topdict, sort_keys=True,
                indent=4, separators=(',', ': ')))

此代码生成以下输出:

{
    "a": {
        "b": {
            "c": {
                "d": {
                    "e": {
                        "file1": {},
                        "file2": {}
                    }
                }
            }
        },
        "f": {
            "g": {
                "h": {
                    "i": {
                        "file3": {},
                        "file4": {}
                    }
                }
            }
        }
    }
}

这篇关于如何将文件路径转换为Treeview?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆