将 os.walk 的结果写入特定的数组位置

Writing results from os.walk and endswith to specific array location

我正在尝试使用过滤器搜索一系列 folder/subfolders,然后将结果写出。如果将结果写入同一个数组,它会起作用,但无法弄清楚如何将匹配定向到特定数组。感谢您的任何建议。

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))

您的匹配列表应该是:

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

然后改变你的:

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

收件人:

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

考虑使用字典:

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))