How to convert a file path into treeview?
Asked Answered
A

1

0

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

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!

Antenna answered 5/8, 2015 at 23:32 Comment(0)
Y
2

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=(',', ': ')))

This code generates the following output:

{
    "a": {
        "b": {
            "c": {
                "d": {
                    "e": {
                        "file1": {},
                        "file2": {}
                    }
                }
            }
        },
        "f": {
            "g": {
                "h": {
                    "i": {
                        "file3": {},
                        "file4": {}
                    }
                }
            }
        }
    }
}
Yaya answered 6/8, 2015 at 2:55 Comment(1)
What does def recursive_dict(): return collections.defaultdict(recursive_dict) do?Antenna

© 2022 - 2024 — McMap. All rights reserved.