473,406 Members | 2,707 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

problem with recursion

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
###

Jul 18 '05 #1
6 1397
take a look at os.walk, it is documented in the library documentation

Jul 18 '05 #2
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
Jul 18 '05 #3
ðÒÉ×ÅÔ vegetax!

03 ÍÁÒÔÁ 2005 × 13:54, vegetax × Ó×ÏÅÍ ÐÉÓØÍÅ Ë All ÐÉÓÁÌ:

v> I need this in order to print a directory tree with htmlgen library
v> which uses nested lists to represent trees.
As you see from output of your code, you simply add items to the only list. Try
this:
v> def rec(f):
res=[]
v> print f
v> for ele in listdir(f):
v> ele=join(f,ele)
v> if isdir(ele):
v> # append the directory name
v> res.append(basename(ele))
res+=[ rec(ele) ]
v> else:
v> res.append(basename(ele))
return res

print rec(dirpath)

Alexander, za**@bk.ru
Jul 18 '05 #4
Alexander Zatvornitskiy wrote:
?????? vegetax!

03 ????? 2005 ? 13:54, vegetax ? ????? ?????? ? All ?????:

v> I need this in order to print a directory tree with htmlgen library
v> which uses nested lists to represent trees.
As you see from output of your code, you simply add items to the only
list. Try this:
v> def rec(f):
res=[]
v> print f
v> for ele in listdir(f):
v> ele=join(f,ele)
v> if isdir(ele):
v> # append the directory name
v> res.append(basename(ele))
res+=[ rec(ele) ]
v> else:
v> res.append(basename(ele))
return res

print rec(dirpath)

Alexander, za**@bk.ru
Thanks it works!

Kent Johnson wrote:
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)


Thanks that works too!

I realy have to improve my recursion skills =(
Anyway having the directory :

+root
+doc1
lesson1
lesson2
+doc3
lesson3
+doc2
lesson4
lesson5

With the code :

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

dirpath = '/devel/python/html/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 HTMLgen.List(rec(dirpath))
</code>

Gives me the espected output as a HTML representation of the tree:

<UL>
<LI>doc1
<UL>
<LI>lesson1.html
<LI>lesson2.html
<LI>doc3
<UL>
<LI>lesson3.html
</UL>
</UL>
<LI>doc2
<UL>
<LI>lesson5.html
<LI>lesson4.html
</UL>
<LI>.tmp3.py.swp

</UL>

Jul 18 '05 #5

How can i use a counter inside the recursive function?
This code gives me the error 'local variable 'c' referenced before
assignment'

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

dirpath = '/devel/python/html/test'
COUNTER = 0

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

print HTMLgen.List(rec(dirpath))
Jul 18 '05 #6
vegetax wrote:
How can i use a counter inside the recursive function?
This code gives me the error 'local variable 'c' referenced before
assignment'
I really don't think it does. I'd believe "local variable 'COUNTER'
referenced before assignment".

Rule one: always copy and paste the traceback ...

I presume you want a count of the directories you have traversed?
#!/usr/bin/python
from os import listdir
from os.path import isdir,join,basename
import HTMLgen

dirpath = '/devel/python/html/test'
COUNTER = 0

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

print HTMLgen.List(rec(dirpath))


regards
Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005 http://www.pycon.org/
Steve Holden http://www.holdenweb.com/
Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: hokiegal99 | last post by:
A few questions about the following code. How would I "wrap" this in a function, and do I need to? Also, how can I make the code smart enough to realize that when a file has 2 or more bad...
45
by: Joh | last post by:
hello, i'm trying to understand how i could build following consecutive sets from a root one using generator : l = would like to produce : , , , ,
11
by: Ken | last post by:
Hello, I have a recursive Sierpinski code here. The code is right and every line works fine by itself. I wish for all of them to call the function DrawSierpinski. But in this cae it only calls...
19
by: snowdy | last post by:
I am using Interactive C with my handboard (68HC11) development system but I've got a problem that I am asking for help with. I am not new to C but learning all the time and I just cant see how to...
16
by: makko | last post by:
Hello, anyone know how to writre a program that take a commandline formula and prints the calculated result? example; $program 1+(2x3(3/2))-8 reagrds; Makkko
10
by: paulw | last post by:
Hi Please give problems that "HAS TO" to use recursion (recursive calls to itself.) Preferrably real world examples, not knights tour. I'm thinking about eliminating the use of stack... ...
1
by: Thomee Wright | last post by:
I'm having a problem with a pair of applications I'm developing. I have a server application which interacts with several instruments, and a client app which connects to the server and provides a...
12
by: NOO Recursion | last post by:
Hi everyone! I am trying to write a program that will search a 12x12 for a thing called a "blob". A blob in the grid is made up of asterisks. A blob contains at least one asterisk. If an...
24
by: proctor | last post by:
hello, i have a small function which mimics binary counting. it runs fine as long as the input is not too long, but if i give it input longer than 8 characters it gives RuntimeError: maximum...
35
by: Muzammil | last post by:
int harmonic(int n) { if (n=1) { return 1; } else { return harmonic(n-1)+1/n; } } can any help me ??
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.