Python-使用部分字符串匹配遍历文件夹中的文件

Python-使用部分字符串匹配遍历文件夹中的文件,python,string,join,operating-system,matching,Python,String,Join,Operating System,Matching,我必须连接/合并两个不同的excel文件,这两个文件是我根据以前的代码创建的,我已经这样做了,以便要连接的文件具有相同的字符串结尾(testaple.xlsx,…dummyApple.xlsx) 我已经设法列出了以结尾作为输出的相关文件,但我仍停留在将两个文件与结尾“Apple”匹配的最后一步。我确信它应该在嵌套的for循环中。我想将它们放入数据帧,然后将两个匹配的文件连接起来。我让它在其他地方作为输出 internal\u joinTest=df\u testApple.merge(df\u

我必须连接/合并两个不同的excel文件,这两个文件是我根据以前的代码创建的,我已经这样做了,以便要连接的文件具有相同的字符串结尾(testaple.xlsx,…dummyApple.xlsx)

我已经设法列出了以结尾作为输出的相关文件,但我仍停留在将两个文件与结尾“Apple”匹配的最后一步。我确信它应该在嵌套的for循环中。我想将它们放入数据帧,然后将两个匹配的文件连接起来。我让它在其他地方作为输出

internal\u joinTest=df\u testApple.merge(df\u dummyApple,on=join\u 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)
现在,在路径字典中有了要分组的路径,因此可以对它们执行任何操作