![]() |
Method not returning?
I wrote a method which is supposed to search a directory (and subdirectories up to 'recurl' levels) for the first instance of a file named 'name', and return the full path to that file.
:
def findfileswithname(path, name, recurl=4, i=0):Quote:
|
I managed to sidestep this problem by using os.walk:
:
filename = 'schedule.xls' |
:
def findfileswithname(path, name, recurl=4, i=0):The code in blue I added/changed to fix a small bug (or what I suspect is a bug). The original if statement read, "if itempath is a directory, and the recusive limit has not been met, then do this". This means that the elif would have read: "if itempath is not a directory, or if it is a directory and the recursive limit was not met, and the item is the item we're searching for, then do this." Thus, if the recursive limit was met, then the function would return directories as well as files. The blue code should fix this up. Also, I removed this line of code: :
if not os.path.isdir(path): return |
Thanks, Arevos. I'm using the code you fixed rather than os.walk() because I can't specify a maximum recursive limit, as far as I know.
|
I have another question. I based the function in my first post on the code for another similar function I wrote, which returns a list of all files with an appropriate extension. However, in this function I don't return the list of files until the very end. Why does this work here when it doesn't in the function I posted previously? Or have I done something wrong here as well?
:
def findfileswithext(path, exts=NC_EXTENSIONS, recurl=3, i=0, files=[]): |
It works, because the "files" list is constant throughout the recursion. Take a look at this line:
:
def findfileswithext(path, exts=NC_EXTENSIONS, recurl=3, i=0, files=[]):I'll give you a quick example of this: :
>>> def foobar(x = []):It usually isn't a good idea to use this functionality, however, as it's somewhat confusing. |
As an aside, there's a lot of common functionality in your two functions that can be abstracted out. If there was a function similar to os.walk, but with a recursive limit, then your functions would be a lot simpler.
Maybe something like this: :
def limited_walk(path, limit, n = 0): |
| All times are GMT -5. The time now is 1:45 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC