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

如何用Python合并两个子文件夹中同名Excel文件至不同工作表

合并跨文件夹的同名Excel文件(按来源分工作表)

现有主文件夹,其下包含folder_a和folder_b两个子文件夹,两个文件夹内各有3个同名的xlsx文件。需要用Python实现以下操作:

  • 检查两个文件夹内的同名文件
  • 将每个同名文件合并为一个新的xlsx文件:
    • 原folder_a中的文件内容存入名为folder_a的工作表
    • 原folder_b中的文件内容存入名为folder_b的工作表
  • 所有合并后的文件输出到主文件夹下的folder_c文件夹

代码实现

import os
import pandas as pd

# 主文件夹路径,请根据实际情况修改
main_folder = r"Desktop\main_folder"

# 定义各文件夹路径
folder_a = os.path.join(main_folder, "folder_a")
folder_b = os.path.join(main_folder, "folder_b")
output_folder = os.path.join(main_folder, "folder_c")

# 创建输出文件夹,不存在则新建
os.makedirs(output_folder, exist_ok=True)

# 获取folder_a中的所有xlsx文件
a_files = [f for f in os.listdir(folder_a) if f.endswith(".xlsx")]

for file_name in a_files:
    # 拼接两个文件夹中对应文件的完整路径
    a_file_path = os.path.join(folder_a, file_name)
    b_file_path = os.path.join(folder_b, file_name)
    
    # 检查folder_b中是否存在同名文件
    if not os.path.exists(b_file_path):
        print(f"跳过文件 {file_name}:folder_b中不存在该文件")
        continue
    
    # 读取两个文件的内容
    df_a = pd.read_excel(a_file_path)
    df_b = pd.read_excel(b_file_path)
    
    # 定义输出文件路径
    output_file = os.path.join(output_folder, file_name)
    
    # 将两个DataFrame写入同一个Excel的不同工作表
    with pd.ExcelWriter(output_file, engine="openpyxl") as writer:
        df_a.to_excel(writer, sheet_name="folder_a", index=False)
        df_b.to_excel(writer, sheet_name="folder_b", index=False)
    
    print(f"已完成合并:{file_name}")

关键说明

  1. 路径处理:用os.path.join拼接路径,避免因Windows/macOS/Linux的路径分隔符差异导致错误
  2. 文件夹创建:os.makedirs的exist_ok=True参数确保即使folder_c已存在也不会抛出异常
  3. 文件检查:遍历folder_a的文件后,先验证folder_b中是否有同名文件,不存在则跳过该文件的合并
  4. Excel写入:pd.ExcelWriter支持在同一个文件中写入多个工作表,index=False避免把DataFrame的索引列写入Excel
  5. 依赖安装:需要提前安装所需库,执行以下命令:
    pip install pandas openpyxl
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 16:39:19