import os
import pandas as pd
dir_path = r"E:\era5land\inter\2003" # 设置工作路径
output_file = r"E:\era5land\inter\2003_merged.xlsx" # 设置输出文件路径
# 新建列表,存放每个文件数据框
frames = []
# 遍历文件夹中的所有文件
for root, dirs, files in os.walk(dir_path):
for file in files:
if file.endswith('.xlsx') or file.endswith('.xls'):
file_path = os.path.join(root, file)
try:
df = pd.read_excel(file_path) # 尝试读取Excel文件
frames.append(df)
print(f"已读取文件: {file_path}")
except Exception as e:
print(f"无法读取文件 {file_path}: {e}")
# 合并所有数据
if frames:
result = pd.concat(frames, ignore_index=True) # 如果frames不为空,则合并数据
try:
result.to_excel(output_file, index=False) # 尝试保存合并后的数据为Excel文件
print(f"数据已保存到 {output_file}")
except Exception as e:
print(f"无法保存文件到 {output_file}: {e}")
else:
print("没有找到任何Excel文件来合并。")
# 如果需要,可以打印合并后的数据的前几行和形状
if not frames:
print("没有数据可以显示。")
else:
print(result.head())
print(result.shape)
代码将把一个文件夹下的所有后缀为.xlsx或.xls的文件读取并合并到一个excel中,这个代码会将第一个读取的表的表头保存,之后的都会忽略表头。
注意:所有要合并的列名应保持一致!!!