python - 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)
现在您在路径字典中拥有了您想要组合在一起的路径,因此您可以对它们做任何您想做的事情
推荐阅读
- javascript - 如何有效地实例化 Vue 组件中的对象?
- unity3d - 从单色纹理生成网格
- android - 如何为每个按钮实施奖励视频广告
- ruby-on-rails - 在 Rails 中,# frozen_string_literal: true 指令与 StripParams 冲突
- vba - 将新电子邮件导出到文件
- angular - pdf.save 不是 Angular 6 中使用的 jspdf 中的函数错误
- sql-server - 存储过程错误:消息 512,级别 16,状态 1,过程 sp_ActFTC,第 64 行子查询返回超过 1 个值
- java - 活动类中的getArguments()?
- ubuntu - 无法在 ubuntu 14.04 LTS 上升级乘客
- wcf - WCF -“未能查找通道以接收传入消息。找不到端点或 SOAP 操作。” 但仅来自一位客户