pynovice
pynovice

Reputation: 7752

Tree file structure from a list in python?

I have a dynamic list which might look like this:

['test_data/reads1.fq', 'test_data/reads_2.fq', 'test_data/new_directory/ok.txt', 
 'test_data/new_directory/new_new_dir/test.txt', 'hello/hello1.txt'] and so on

I want to construct hierarchy tree structure from this file:

test_data
   files
    new_directory
    file
    new_new_dir
       file

hello

How can I do this in Python?

Following code will construct list to the root of the file. How can I proceed after that?

 [i.split('/') for i in a]

Upvotes: 2

Views: 145

Answers (2)

Marcelo Cantos
Marcelo Cantos

Reputation: 185962

You can build a hierarchy quite simply as follows:

t = {}
for p in pp:
    tt = t
    for c in p.split('/'):
        tt = tt.setdefault(c, {})

The only catch is that leaves are represented as keys with empty dictionaries:

{'test_data': {'reads1.fq'    : {},
               'reads_2.fq'   : {},
               'new_directory': {'ok.txt'     : {},
                                 'new_new_dir': {'test.txt': {}}}},
 'hello'    : {'hello1.txt': {}}}

Upvotes: 4

unwind
unwind

Reputation: 399959

Here's a very rough algorithm:

  • For each string in the list:
    • Split it into path components
    • For each component:
      • Check if there's a tree node of that name at the current level, else create it
      • If non-leaf, make the node just visited (or created) the current one

Upvotes: 4

Related Questions