[Tutor] "return" and recursive functions

Hans Nowak ivnowa@hvision.nl
Sun, 13 Jun 1999 18:25:22 +0200


Jon Coby wrote:

> Problem: I need the following code to return search results for the given
> directory and it's sub-directories. As it is, it's returning "hits" only for
> the root directory. Any ideas as to how to work around this?
> 
> Jon Cosby
> 
> def getFile(text, dir):
>     hits = []
>     dl = os.listdir(dir)
>     text = string.lower(text)
>     for d in dl:
>         d = dir + '\\' + d
>         if os.path.isfile(d):
>             hits.extend(searchtext(text, d))     # Search file for word
>         elif os.path.isdir(d):
>             getFile(text, d)         # Do sub-directories
>     return hits

'hits' is a local variable... every time getFile is called 
recursively, a new instance is created locally *and* discarded upon 
return. Calls to getFile do not influence the hits list in the 
calling function, they only create a new hits locally in the callee. 
What you need to do it make 'hits' accumulate search results... maybe 
like this:

change this line:

    getFile(text, d)         # Do sub-directories

to:

    hits.append(getFile(text,d))

I haven't really tested it so this might or might not work the way 
you want it. 

Veel liefs,

--Hans Nowak (ivnowa@hvision.nl)
Homepage: http://fly.to/zephyrfalcon