在子文件夹中搜索标题包含特定Python文本的最近的excel文件



我最近才开始用Python编程,我发现了我的第一个问题,经过几天的研究,我似乎无法弄清楚。希望论坛上有人能帮帮我。

这句话的语境是:在我们公司,我有多个文件夹和子文件夹。在这些子文件夹中我们有excel文件名为:

  • 物品供求"date".xlsx
  • Backorder report" date".xlsx
  • 产品可用报告"日期".xlsx

每天早上我们的IT下载一个包含这些名称和今天日期的新文件。例如今天的图表是这样的:物品供给需求23-06-22.xlsx

目标:我想找到最近的Excel文件在我们的子文件夹,其中包含名称"项目供应和需求"我已经知道如何找到最近的Excel文件与glob。一团的功能。但是,我似乎无法在名称部分添加额外的过滤器。在我已经有了的代码下面:

import sys
import csv
import pandas as pd
import glob
import os.path
import pathlib
import re
#search for all Excel files
files = glob.glob(r"Pathname***.xlsx", recursive = True)
#find most recent Item Supply Demand report
text_files = str(files)
if 'Item Supply Demand' in text_files:
max_file = max(files, key=os.path.getctime)
#Add the file to the dataframe 
df = pd.read_excel(max_file)
df

有没有人知道我的代码目前缺失或错误?

提前感谢您对我们的帮助!

欢呼,Kav

试试这个,你已经成功了99%。

files = glob.glob(r"Pathname***Item Supply Demand*.xlsx", recursive = True)

那么我想下面的代码块可以去掉条件变成

# find most recent Item Supply Demand report
max_file = max(files, key=os.path.getctime)

注意-我还没有检查语法是否会做你想要的-甚至工作-我假设它为你工作,因为它不是你问题的焦点。

编辑:刚刚检查过了-很好-它会给你想要的。

文件"已经是字符串列表。您可以创建只匹配子字符串的字符串列表,然后使用该列表。

wanted_file_substring = "Item Supply Demand"
matching_files = [specific_file for specific_file in files if wanted_file_substring in specific_file]
max_file = max(matching_files, key=os.path.getctime)

编辑我的答案:无论你选择哪一个答案,你都需要在&;if&;之外初始化变量。语句或将read_excel行移动到if语句中。如果没有找到您想要的文件,您的程序将出错,因为pandas试图引用一个不存在的变量。

修改if语句为:

if files:
max_file = max(.....)
pd.read_excel(max_file)

最新更新