> I have a piece of code that I need some help with. It is > supposed (in my mind at least) take two arguments, a start > path and a file extension. Then when called it should return > each of the file paths that are found matching the criteria. > It is only returning the first file that it finds. What am I > doing wrong?
1 def findFileExt(startPath, fileExt): 2 for root, dirs, files in os.walk(startPath): 3 for file in files: 4 if file.endswith(fileExt): 5 filePath = str(os.path.join(root, file)) 6 return filePath On line 7, you return from the function which prevents the remainder of the code in the function/loop from being processed. You'd either have go gather them all in a list and then return that gathered list: 1 def findFileExt(startPath, fileExt): + results = [] 2 for root, dirs, files in os.walk(startPath): 3 for file in files: 4 if file.endswith(fileExt): 5 filePath = str(os.path.join(root, file)) -6 return filePath + results.append(filePath) + return results or, you could write it as a generator: 1 def findFileExt(startPath, fileExt): 2 for root, dirs, files in os.walk(startPath): 3 for file in files: 4 if file.endswith(fileExt): 5 filePath = str(os.path.join(root, file)) -7 return filePath + yield filePath which can then be used like for thing in findFileExt(src_path, ext): do_something(thing) -tkc -- http://mail.python.org/mailman/listinfo/python-list