【问题标题】:Python - Iterate through files in folder with partial string matchesPython - 遍历文件夹中具有部分字符串匹配的文件
【发布时间】:2021-01-19 11:09:48
【问题描述】:

我必须加入/合并我从以前的代码创建的两个不同的 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)

【问题讨论】:

    标签: python string join operating-system matching


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-07-06
      • 2017-03-03
      • 2011-08-10
      • 1970-01-01
      • 2022-01-23
      • 2014-04-24
      • 2017-02-08
      • 2021-12-23
      • 2015-06-17
      相关资源
      最近更新 更多