读取子文件夹Excel文件时生成空DataFrame的问题排查
问题描述
Excel文件存于以国家命名的子文件夹中,编写代码读取文件并提取工作表数据,代码运行无报错但得到空DataFrame。代码如下:
import openpyxl import pandas as pd import os # Define the parent folder path with double backslashes parent_folder = '..../data/Pilot_data/' # Create empty dataframes for each sheet merged_allowances_df = pd.DataFrame() merged_allowances_convert_df = pd.DataFrame() merged_basic_salaries_df = pd.DataFrame() merged_basic_salaries_convert_df = pd.DataFrame() # Loop through sub-folders for each country for country_folder in os.listdir(parent_folder): country_folder_path = os.path.join(parent_folder, country_folder) if os.path.isdir(country_folder_path): # Find all Excel files in the current country folder excel_files = [file for file in os.listdir(country_folder_path) if file.endswith('.xlsx')] # Loop through Excel files in the current country folder for excel_file in excel_files: excel_file_path = os.path.join(country_folder_path, excel_file) print(excel_file_path) # Read Excel data if 'Allowances' in excel_file: try: allowances_df = pd.read_excel(excel_file_path, 'Allowances', header=None, skiprows=1) # Process allowances_df as needed merged_allowances_df = merged_allowances_df.append(allowances_df, ignore_index=True) except Exception as e: print(f"Error reading 'Allowances' sheet in {excel_file}: {str(e)}") # Now you have separate merged dataframes for each sheet print("Merged Allowances DataFrame:") print(merged_allowances_df.head())
运行时打印的文件路径:
..../data/Pilot_data/Angola\\DB_Salary_Study_2021_Angola.xlsx ..../data/Pilot_data/Angola\\DB_Salary_Study_2021_Angola.xlsx
问题原因与解决办法
核心问题:文件名判断不匹配
代码里用if 'Allowances' in excel_file筛选要读取的文件,但实际文件名DB_Salary_Study_2021_Angola.xlsx完全不含Allowances字符串,导致读取Excel的代码块根本没执行,自然得到空DataFrame。次要问题:重复打印文件路径
同一个文件被打印两次,大概率是对应国家文件夹里存在两个同名文件(比如副本),可以检查文件夹内的文件情况,删除重复项避免重复处理。路径斜杠问题
打印路径里出现/和\\混合,是因为手动写的父路径用了/,而os.path.join在Windows环境下会用\\,这属于显示问题,不会影响文件读取,无需处理。
修正方案
调整文件判断逻辑:如果文件包含
Allowances工作表但文件名不含该关键词,可改为判断工作表是否存在,同时建议用pd.concat替代已弃用的append:# 替换原有的读取代码部分 try: # 先获取文件中的所有工作表名 excel_file_obj = pd.ExcelFile(excel_file_path) if 'Allowances' in excel_file_obj.sheet_names: allowances_df = pd.read_excel(excel_file_obj, 'Allowances', header=None, skiprows=1) merged_allowances_df = pd.concat([merged_allowances_df, allowances_df], ignore_index=True) except Exception as e: print(f"Error processing {excel_file}: {str(e)}")清理重复文件:检查国家文件夹内的Excel文件,删除重复文件,避免重复处理。
内容的提问来源于stack exchange,提问作者Livingstone
相关产品推荐
相关产品推荐

