Python 将结果从os.walk和endswith写入特定数组位置

Python 将结果从os.walk和endswith写入特定数组位置,python,arrays,os.walk,ends-with,Python,Arrays,Os.walk,Ends With,我正在尝试使用过滤器搜索一系列文件夹/子文件夹,然后写出结果。如果将结果写入同一数组,但无法确定如何将匹配定向到特定数组,则该方法是有效的。谢谢你的建议 matchlist = [ ['*.csv'], ['*.txt'], ['*.jpg'], ['*.png'] ] filearray = [ [],[],[],[] ] for root, dirs, files in os.walk(folderpath): for file in files: for entry

我正在尝试使用过滤器搜索一系列文件夹/子文件夹,然后写出结果。如果将结果写入同一数组,但无法确定如何将匹配定向到特定数组,则该方法是有效的。谢谢你的建议

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


考虑使用字典:

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

您应该使用
dict
对象,但您的问题是
匹配列表中的
条目
是其他单元素列表,其中包含您实际使用的字符串。请注意,您从未使用过数组。
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))