Reputation: 43
I'm trying to walk a directory, retrieve all files within that directory ending with a certain extension, and write that file to a list. This is list is supposed to be returned after the function is done doing its job.
def grabFiles(source,ext):
import fnmatch
import os
matches = [] #tmp var which is used to return the files matching the search mask.
for root, dirnames, filenames in os.walk(source): #for each folder & subfolder do:
for filename in fnmatch.filter(filenames, ext): #and for each file found like that do:
matches.append(os.path.join(root, filename))#append the file name&directory to the "matches" variable.
return(matches) #return the content of matches
Now when I run this using the following:
ext=[".caf", ".lmg", ".chr", ".cdf", ".dds", ".tif", ".mtl", ".cgf", ".cga"]
for filetype in ext:
files= nPy.grabFiles("D:\\01_SVN\\01_DE\\trunk\\Game",filetype)
print files
I believe it should be returning me a list with files for each extension in my ext list, right? Instead it returns a [ ] for each item in the ext list.
If I fire this thing without using a definition, it works just fine :/
import fnmatch
import os
source ="D:\\01_SVN\\01_DE\\trunk\\Game"
extension = ["*.mtl","*.tif","*.chr"]
matches = []
for filetype in extension:
for root, dirnames, filenames in os.walk("%s" % (source)):
for filename in fnmatch.filter(filenames, "%s" % (filetype)):
matches.append(os.path.join(root, filename))
print matches
I've been staring at this for over an hour, and Im afraid im practically blind to my own script by now :< Im either incapable of returning a dang list, or Im misunderstanding how returning works - but it should be passing the list from matches to a new var without a problem, no?
Upvotes: 0
Views: 112
Reputation: 10582
I believe you are matching .ext
instead of *.ext
. Try adding the star to match the name and it should work.
def grabFiles(source,ext):
import fnmatch
import os
matches = []
for root, dirnames, filenames in os.walk(source):
for filename in fnmatch.filter(filenames, '*' + ext):
matches.append(os.path.join(root, filename))
return matches
About you programming style:
endswith
rather that fnmatch.filtersource ="D:\\01_SVN\\01_DE\\trunk\\Game"
use source=r"D:\01_SVN\01_DE\trunk\Game"
Upvotes: 2