0

I'm trying to search a series of folder/subfolders using filters, and then write the results out. It works if results are written to the same array, but can't figure out how to direct matches to specific arrays. Thanks for any suggestions.

matchlist = [ ['*.csv'], ['*.txt'], ['*.jpg'], ['*.png'] ]
filearray = [ [],[],[],[] ]
for root, dirs, files in os.walk(folderpath):
    for file in files:
        for entry in matchlist:
            if file.endswith(entry):
                 filearray[TheAppropriateSubArray].append(os.path.join(root, file))
rNOde
  • 59
  • 5
  • You should use a `dict` object, but your problem is that your `entry` inside `matchlist` *are other single-element lists* which contain the strings you actually one. Note, nowhere have you used an array. – juanpa.arrivillaga Feb 21 '18 at 20:21

2 Answers2

1

Your match list should be:

matchlist = ['.csv', '.txt', '.jpg', '.png']

Then change your:

    for entry in matchlist:
        if file.endswith(entry):
             filearray[TheAppropriateSubArray].append(os.path.join(root, file))

To:

    for i, entry in enumerate(matchlist):
        if file.endswith(entry):
             filearray[i].append(os.path.join(root, file))
llllllllll
  • 16,169
  • 4
  • 31
  • 54
0

Consider using dictionary:

filearrays = { '.csv':[],'.txt':[],'.jpg':[],'.png':[] }
for root, dirs, files in os.walk(folderpath):
    for file in files:
        filename, fileext = os.path.splitext(file)
        if fileext in filearrays:
            filearrays[fileext].append(os.path.join(root, file))
Yunkai Xiao
  • 191
  • 12