且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将文件路径转换为Treeview?

更新时间:2023-10-13 13:27:10

从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": {}
                    }
                }
            }
        }
    }
}