[英]Ignoring Part of Filename Using pd.read_excel
我是 Python 和 Pandas 的新手,正在尋求幫助。
我已經編寫了 Python 代碼,以便讀取每月 Excel 文件,操作數據並將 append 到另一個文件。 我的問題是每個月原始文件都會重命名以匹配生成的年份和日期,例如上個月的是“2022 McCarthy LEM_2022 Financial Reporting_20220329”。
有沒有辦法使用 pd.read_excel 並讓它在包含“McCarthy”“LEM”或“Financial Reporting”的文件夾中獲取 any.xlsx 文件名?
我目前只使用以下簡單代碼:
pd.read_excel("2022 McCarthy LEM_2022 Financial
Reporting_20220329.xlsx", sheet_name = "2022 Billable Work Order
Data")
還是我應該采取不同的方法來解決這個問題?
理想情況下,我會在 email 中收到報告,將報告保存到一個文件夾中,然后想啟動 Python 腳本,而不必在代碼中更改文件名。
感謝您的任何想法和幫助!
您可以使用 python 標准庫中包含的glob
之類的東西。
import glob
substring_list = ["McCarthy", "LEM", "Financial Reporting"]
file_lists = glob.glob("path/to/directory/*.xlsx")
for file in file_lists:
if any(substring in file for substring in substring_list):
pd.read_excel(file, sheet_name = "2022 Billable Work Order Data")
我使用了更基本的方法來檢查 substring 是否在字符串中,而不是在正則表達式中,但是glob
也可以接受正則表達式,所以你可以那樣做。 但是,如果您只對一組特定的子字符串感興趣,那么這可能更容易理解並在需要時進行更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.