You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过部分文件名读取Excel文件并导入DataFrame

按文件名前缀批量导入Excel文件为DataFrame

你可以用两种简单的方法实现批量读取所有以Report_Lineup_Export开头的Excel文件:

方法1:用glob模块快速匹配文件

glob模块支持通配符匹配文件名,能直接定位到符合条件的文件:

import pandas as pd
import glob

# 定义目标文件夹路径
folder_path = 'C:/Users/fernandom/OneDrive/08_Scripts/01_Python/'
# 生成匹配规则:前缀+任意字符+.xls
file_pattern = f'{folder_path}Report_Lineup_Export*.xls'
# 获取所有符合条件的文件路径列表
matching_files = glob.glob(file_pattern)

# 两种处理方式可选:
# 方式1:把每个文件的DataFrame存在字典里,用文件名做键
dfs_dict = {}
for file in matching_files:
    filename = file.split('/')[-1]
    dfs_dict[filename] = pd.read_excel(file)

# 方式2:如果所有文件结构一致,直接合并成一个大DataFrame
combined_df = pd.concat([pd.read_excel(file) for file in matching_files], ignore_index=True)

方法2:用os模块遍历筛选文件

如果不想用glob,也可以手动遍历文件夹,筛选符合前缀的文件:

import pandas as pd
import os

folder_path = 'C:/Users/fernandom/OneDrive/08_Scripts/01_Python/'
matching_files = []

# 遍历文件夹下的所有文件
for filename in os.listdir(folder_path):
    # 判断文件名前缀和后缀
    if filename.startswith('Report_Lineup_Export') and filename.endswith('.xls'):
        full_path = os.path.join(folder_path, filename)
        matching_files.append(full_path)

# 后续读取/合并操作和方法1一致
combined_df = pd.concat([pd.read_excel(file) for file in matching_files], ignore_index=True)

注意事项

  • 如果不同文件的表格结构不一样,合并时会出现列不匹配的问题,这种情况建议用字典单独存储每个文件的DataFrame,逐个处理。
  • 路径里的斜杠可以用/或者转义的\\,避免出现路径解析错误。

内容的提问来源于stack exchange,提问作者Fernando Martins

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 21:30:58