DONGCHAO

Good Luck To You!

python合并excel

python 读取一个文件夹下的全部子文件夹中的excel,如果子文件夹中的excel文件数量大于1,则将当前子文件夹下的全部excel合并为一个以子文件夹名命名的excel

# -*- coding: utf-8 -*-
# @Time    : 2023/6/14 9:45
# @Author  : JDC
# @File    : merge_excel.py
# @Software: PyCharm
# python 读取一个文件夹下的全部子文件夹中的excel,如果子文件夹中的excel文件数量大于1,则将当前子文件夹下的全部excel合并为一个以子文件夹名命名的excel

import os

import pandas as pd


# 遍历文件夹及其子文件夹
def get_all_files(path):
    for root, dirs, files in os.walk(path):
        for file in files:
            yield os.path.join(root, file)


# 筛选Excel文件
def get_excel_files(path):
    for file in get_all_files(path):
        if os.path.splitext(file)[-1] in ['.xlsx', '.xls']:
            yield file


# 合并所有Excel文件
def merge_excel_files(path):
    dfs = []
    for file in get_excel_files(path):
        dfs.append(pd.read_excel(file))
    if len(dfs) > 0:
        return pd.concat(dfs)
    return None


# 将当前子文件夹下的所有Excel文件合并为一个以子文件夹名命名的Excel文件
def merge_excel_files_by_folder(path):
    folder_name = os.path.basename(path)
    dfs = []
    for file in get_excel_files(path):
        dfs.append(pd.read_excel(file))
    if len(dfs) > 1:
        df = pd.concat(dfs)
        df.to_excel(f'{folder_name}.xlsx', index=False)
        print('合并了文件夹 {} 下的 {} 个Excel文件为一个文件:{}'.format(path, len(dfs), folder_name))


# 遍历文件夹及其子文件夹,将当前子文件夹下的所有Excel文件合并为一个以子文件夹名命名的Excel文件
def merge_all_excel_files(path):
    for root, dirs, files in os.walk(path):
        for dir1 in dirs:
            dir_path = os.path.join(root, dir1)
            merge_excel_files_by_folder(dir_path)


if __name__ == "__main__":
    parent_folder = 'D:\\example\\download'
    merge_all_excel_files(parent_folder)


  • 评论列表

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

«    2024年1月    »
1234567
891011121314
15161718192021
22232425262728
293031
网站分类
搜索
最新留言
文章归档
友情链接
  • 订阅本站的 RSS 2.0 新闻聚合

Powered By Z-BlogPHP 1.7.2

© 2023 DONGCHAO.ORG.CN All Rights Reserved. 版权所有:豫ICP备2023000417号-1