problem with recursion

vegetax vegeta.z at gmail.com
Thu Mar 3 12:54:21 EST 2005


I am trying to make convert a directory "tree" in a list of list, but cant
find the algoritm =( ,for example a directory tree like :

+root
 +doc
   ele1
   ele2
   +doc3
    ele3
 +doc2
  ele4

 ele5

should convert into:

root[
     doc,
     [ele1,ele2,doc3,[ele3]],
     doc2,
     [ele4],
     ele5
    ]

I dont have any idea how to do it =( ,so far i get something like
this : [doc1,ele1,ele2,doc3,ele3,doc2,ele4,ele5] instead of
       [doc1,[ele1,ele2,doc3,[ele3]],doc2,[ele4],ele5]

I need this in order to print a directory tree with htmlgen library which
uses nested lists to represent trees.

#!/usr/bin/python
from os import listdir
from os.path import isdir,join,basename

dirpath  = '/tmp/test/'
res = []

def rec(f):
    print f
    for ele in listdir(f):
        ele = join(f,ele)
        if isdir(ele):
            # append the directory name  
          res.append(basename(ele))
            rec(ele)
        else :
            res.append(basename(ele))

rec(dirpath)
print res
###




More information about the Python-list mailing list