首页 > 解决方案 > 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)

标签: pythonstringjoinoperating-systemmatching

解决方案


如果你想在嵌套的 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)

现在您在路径字典中拥有了您想要组合在一起的路径,因此您可以对它们做任何您想做的事情


推荐阅读