Python-遍历文件夹中具有部分字符串匹配项的文件

问题描述

我必须合并/合并从上一个代码创建的两个不同的excel文件,并且已经做到了,因此要合并的文件具有相同的字符串结尾(testApple.xlsx,... dummyApple.xlsx

我设法列出了以结尾结尾的相关文件作为输出,但是我停留在例如将两个文件结尾为“ Apple”的最后一步。我确定它应该在嵌套的for循环内。我想将它们放入数据框,然后将两个匹配的文件合并。我让它在其他地方工作

inner_joinTest = df_testApple.merge(df_dummyApple,on = join_list,how = 'left')

示例代码如下:


listTest = ['apple','orange']

directory = r"C:\Users\Documents\Fruit"
for entry in os.scandir(directory):
    for i in listTest:
        if entry.is_file() and entry.name.endswith(i + ".xlsx"):
            print(entry.path)

解决方法

如果您想在嵌套的for循环之外进行合并,您要做的就是将路径保存到列表或字典中,然后您可以对它们进行任何操作。

listTest = ['apple','orange']
paths = {"apple":[],"orange":[]}

directory = r"C:\Users\Documents\Fruit"
for entry in os.scandir(directory):
    for i in listTest:
        if entry.is_file() and entry.name.endswith(i + ".xlsx"):
            paths[i].append(entry.path)

现在您在paths字典中将想要的路径分组在一起,因此您可以对它们进行任何操作