Reputation: 41
i need a program that takes as parameters the name of a file and the pathname of a folder and search for the file in the folder and any folder contained within it, directly or indirectly. The function should return the pathname of the file, if found, or None if the file cannot be found in the folder or in any subdirectory of the folder. The function must be recursive.
here is my code:
def search(fname, path):
for item in os.listdir(path):
next = os.path.join(path, item)
try:
search(next,fname)
except:
return next
it should look like something along the lines of:
>>>search('fileA.txt', 'test')
'test\\fileA.txt'
>>>search('fileB.txt', 'test')
'text\\folder2\\fileB.txt'
ect. but i can only get my code to find fileA.txt, no matter what file i tell it to look for.
I asked the teacher for some help, this is what she told me:
**I see several problems:
Upvotes: 0
Views: 425
Reputation: 2114
Your recursion elements are mixed up. Try search(fname, next)
.
Also, as mentioned by Brendan, you should be using if/else
, not try/except
, since no errors are being thrown here.
And last of all, you don't seem to have a base case (e.g., no further directories to traverse), a final condition which will terminate recursion and prevent infinite looping/recursion.
Upvotes: 2
Reputation: 150977
You need a recursion termination condition. Think about the conditions under which the function should return and the conditions under which it should keep looking. Then write an if/else
block to test for those conditions. If the return condition holds, return the correct value. Otherwise, return the result of a recursive call. In other words, it should look like this (schematically):
def search(old_args)
if condition:
return 'value' # recursion terminates and value is returned
else: # all the way down the call stack
return search(new_args) # continue recursion until `condition` holds &
# pass the result down the stack with `return`
Upvotes: 0
Reputation: 348
You could use os.walk() to do this:
import os
def search(fname, path):
for root, dirs, files in os.walk(path):
if fname in files:
return os.path.join(root, file)
else:
return None
Upvotes: 1