0

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

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

2 回答 2

1

您的匹配列表应该是:

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))
于 2018-02-21T20:09:13.870 回答
0

考虑使用字典:

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))
于 2018-02-21T20:10:14.820 回答