以标题中的特定单词阅读excel

我有一个文件夹,其中可能有也可能没有多个Excel文件。

The name of the excel files can change with time, but there would be one specific keyword that will always be in the name of the excel. For test purposes, let the keyword be Fruits

For the excel which have fixed name like Fruits_Pineapple.xlsx the code works:

import pandas as pd
pd.read_excel(r'c:\mypath\Fruits_Pineapple.xlsx')

But I can have excel file like Fruits_Pineapple, Fruits_Apple,Vegetables etc. I want to know how can I read the excel with contains functionality.

我已经搜索过了,但令人惊讶的是找不到任何解决方案!

评论
  • 独唱情歌
    独唱情歌 回复

    Since you have no idea of how many (if any) excel files are valid in your folder, you can do the following using glob-

    import glob
    import pandas as pd
    
    excel_list = glob.glob("*Fruits*.xlsx") 
    #or whatever extension you have, you can give a relative path or complete path.
    for excel in excel_list:
        pd.read_excel(excel)
        #Whatever else you need to do below