problem with recursion

Kent Johnson kent37 at tds.net
Thu Mar 3 13:54:07 EST 2005


vegetax wrote:
> 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 :
> 
> #!/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

The problem is that you are always appending individual names to the same list. If you make rec() 
return a list and append that to the current list you get what you want:

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

dirpath  = '/tmp/test/'

def rec(f):
     res = []
     for ele in listdir(f):
         res.append(ele)
         ele = join(f,ele)
         if isdir(ele):
             res.append(rec(ele))
     return res

print rec(dirpath)

Kent



More information about the Python-list mailing list