如何使用 Python 将多个 excel 文件合并为一个文件?
off999 2024-12-17 15:42 19 浏览 0 评论
通常,我们正在处理 Excel 文件,我们肯定遇到过需要将多个 Excel 文件合并为一个文件的情况。传统方法一直是在 excel 中使用 VBA 代码,它可以完成这项工作,但是不太容易理解。另一种方法是手动将长Excel文件复制到一个文件中,这不仅耗时,麻烦,而且容易出错。
使用 python中的Pandas 模块即可轻松快速地完成此任务。如果未安装Pandas模块在终端中使用以下命令:
pip install pandas
1、导入库
import os
import pandas as pd
- os: 用于与操作系统交互,特别是文件和目录操作。
- pandas: 一个强大的Python数据处理库,用于读取和写入Excel文件
2、定义函数
def merge_excel_files(folder_path, output_file):
- folder_path: 包含要合并的Excel文件的文件夹路径。
- output_file: 保存合并数据的输出文件名。
3、列出Excel文件
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx') or f.endswith('.xls')
- 这行代码列出了指定文件夹中所有扩展名为.xlsx或.xls的文件。
4、读取并合并Excel文件
data_frames = []
for file in excel_files:
file_path = os.path.join(folder_path, file)
try:
data = pd.read_excel(file_path)
data_frames.append(data)
except Exception as e:
print(f"读取文件 {file} 时出错: {e}")
- 创建一个空的列表data_frames来存储每个Excel文件的数据。
- 脚本遍历每个Excel文件,将其内容读取到一个DataFrame中,并将其追加到data_frames列表中。
- 如果读取文件时发生错误,会打印错误信息。
5、合并数据
merged_data = pd.concat(data_frames, ignore_index=True)
- 使用pd.concat函数将所有DataFrame对象合并成一个DataFrame,并忽略索引。
6、保存合并后的数据
merged_data.to_excel(output_file, index=False)
print(f"合并后的文件已保存为 {output_file}")
- 将合并后的数据保存到指定的输出文件中,不包括索引。
- 打印一条消息,确认文件已保存。
7、错误处理
except Exception as e:
print(f"处理文件夹 {folder_path} 时出错: {e}")
- 如果在处理文件夹或合并数据时发生错误,会打印错误信息。
8、使用示例
folder_path = 'C:/Users/standee/Desktop/test'
output_file = 'merged_excel.xlsx'
merge_excel_files(folder_path, output_file)
- 这部分脚本设置文件夹路径和输出文件名,然后调用merge_excel_files函数执行合并。
完整代码如下:
import os
import pandas as pd
def merge_excel_files(folder_path, output_file):
try:
# 获取文件夹中的所有Excel文件
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx') or f.endswith('.xls')]
# 读取并合并所有Excel文件
data_frames = []
for file in excel_files:
file_path = os.path.join(folder_path, file)
try:
data = pd.read_excel(file_path)
data_frames.append(data)
except Exception as e:
print(f"读取文件 {file} 时出错: {e}")
# 使用pd.concat合并数据
merged_data = pd.concat(data_frames, ignore_index=True)
merged_data.to_excel(output_file, index=False)
print(f"合并后的文件已保存为 {output_file}")
except Exception as e:
print(f"处理文件夹 {folder_path} 时出错: {e}")
# 使用示例
folder_path = 'C:/Users/standee/Desktop/test'
output_file = 'merged_excel.xlsx'
merge_excel_files(folder_path, output_file)
需合并的数据:
“001.xlsx”
OrderDate | Region | City | Category | Product | Quantity | UnitPrice | TotalPrice |
2020/1/1 | East | Boston | Bars | Carrot | 33 | 1.77 | 58.41 |
2020/1/4 | East | Boston | Crackers | Whole Wheat | 87 | 3.49 | 303.63 |
2020/1/7 | West | Los Angeles | Cookies | Chocolate Chip | 58 | 1.87 | 108.46 |
2020/1/10 | East | New York | Cookies | Chocolate Chip | 82 | 1.87 | 153.34 |
2020/1/13 | East | Boston | Cookies | Arrowroot | 38 | 2.18 | 82.84 |
2020/1/16 | East | Boston | Bars | Carrot | 54 | 1.77 | 95.58 |
2020/1/19 | East | Boston | Crackers | Whole Wheat | 149 | 3.49 | 520.01 |
2020/1/22 | West | Los Angeles | Bars | Carrot | 51 | 1.77 | 90.27 |
2020/1/25 | East | New York | Bars | Carrot | 100 | 1.77 | 177 |
2020/1/28 | East | New York | Snacks | Potato Chips | 28 | 1.35 | 37.8 |
2020/1/31 | East | Boston | Cookies | Arrowroot | 36 | 2.18 | 78.48 |
2020/2/3 | East | Boston | Cookies | Chocolate Chip | 31 | 1.87 | 57.97 |
2020/2/6 | East | Boston | Crackers | Whole Wheat | 28 | 3.49 | 97.72 |
2020/2/9 | West | Los Angeles | Bars | Carrot | 44 | 1.77 | 77.88 |
“002.xlsx”
OrderDate | Region | City | Category | Product | Quantity | UnitPrice | TotalPrice |
2020/3/29 | East | Boston | Cookies | Oatmeal Raisin | 193 | 2.84 | 548.12 |
2020/4/1 | West | Los Angeles | Bars | Carrot | 58 | 1.77 | 102.66 |
2020/4/4 | West | Los Angeles | Snacks | Potato Chips | 68 | 1.68 | 114.24 |
2020/4/7 | East | New York | Bars | Carrot | 91 | 1.77 | 161.07 |
2020/4/10 | East | New York | Crackers | Whole Wheat | 23 | 3.49 | 80.27 |
2020/4/13 | West | San Diego | Snacks | Potato Chips | 28 | 1.68 | 47.04 |
2020/4/16 | East | Boston | Bars | Carrot | 48 | 1.77 | 84.96 |
2020/4/19 | East | Boston | Snacks | Potato Chips | 134 | 1.68 | 225.12 |
2020/4/22 | West | Los Angeles | Bars | Carrot | 20 | 1.77 | 35.4 |
2020/4/25 | East | New York | Bars | Carrot | 53 | 1.77 | 93.81 |
2020/4/28 | East | New York | Snacks | Potato Chips | 64 | 1.68 | 107.52 |
2020/5/1 | West | San Diego | Cookies | Chocolate Chip | 63 | 1.87 | 117.81 |
2020/5/4 | East | Boston | Bars | Bran | 105 | 1.87 | 196.35 |
2020/5/7 | East | Boston | Cookies | Oatmeal Raisin | 138 | 2.84 | 391.92 |
运行Python:
D:\python\python.exe D:\pycharm\pythonProject\excelmerge.py
合并后的文件已保存为 merged_excel.xlsx
Process finished with exit code 0
合并后生成一个merged_excel.xlsx的文件:
OrderDate | Region | City | Category | Product | Quantity | UnitPrice | TotalPrice |
2020/1/1 | East | Boston | Bars | Carrot | 33 | 1.77 | 58.41 |
2020/1/4 | East | Boston | Crackers | Whole Wheat | 87 | 3.49 | 303.63 |
2020/1/7 | West | Los Angeles | Cookies | Chocolate Chip | 58 | 1.87 | 108.46 |
2020/1/10 | East | New York | Cookies | Chocolate Chip | 82 | 1.87 | 153.34 |
2020/1/13 | East | Boston | Cookies | Arrowroot | 38 | 2.18 | 82.84 |
2020/1/16 | East | Boston | Bars | Carrot | 54 | 1.77 | 95.58 |
2020/1/19 | East | Boston | Crackers | Whole Wheat | 149 | 3.49 | 520.01 |
2020/1/22 | West | Los Angeles | Bars | Carrot | 51 | 1.77 | 90.27 |
2020/1/25 | East | New York | Bars | Carrot | 100 | 1.77 | 177 |
2020/1/28 | East | New York | Snacks | Potato Chips | 28 | 1.35 | 37.8 |
2020/1/31 | East | Boston | Cookies | Arrowroot | 36 | 2.18 | 78.48 |
2020/2/3 | East | Boston | Cookies | Chocolate Chip | 31 | 1.87 | 57.97 |
2020/2/6 | East | Boston | Crackers | Whole Wheat | 28 | 3.49 | 97.72 |
2020/2/9 | West | Los Angeles | Bars | Carrot | 44 | 1.77 | 77.88 |
2020/3/29 | East | Boston | Cookies | Oatmeal Raisin | 193 | 2.84 | 548.12 |
2020/4/1 | West | Los Angeles | Bars | Carrot | 58 | 1.77 | 102.66 |
2020/4/4 | West | Los Angeles | Snacks | Potato Chips | 68 | 1.68 | 114.24 |
2020/4/7 | East | New York | Bars | Carrot | 91 | 1.77 | 161.07 |
2020/4/10 | East | New York | Crackers | Whole Wheat | 23 | 3.49 | 80.27 |
2020/4/13 | West | San Diego | Snacks | Potato Chips | 28 | 1.68 | 47.04 |
2020/4/16 | East | Boston | Bars | Carrot | 48 | 1.77 | 84.96 |
2020/4/19 | East | Boston | Snacks | Potato Chips | 134 | 1.68 | 225.12 |
2020/4/22 | West | Los Angeles | Bars | Carrot | 20 | 1.77 | 35.4 |
2020/4/25 | East | New York | Bars | Carrot | 53 | 1.77 | 93.81 |
2020/4/28 | East | New York | Snacks | Potato Chips | 64 | 1.68 | 107.52 |
2020/5/1 | West | San Diego | Cookies | Chocolate Chip | 63 | 1.87 | 117.81 |
2020/5/4 | East | Boston | Bars | Bran | 105 | 1.87 | 196.35 |
2020/5/7 | East | Boston | Cookies | Oatmeal Raisin | 138 | 2.84 | 391.92 |
相关推荐
- 让 Python 代码飙升330倍:从入门到精通的四种性能优化实践
-
花下猫语:性能优化是每个程序员的必修课,但你是否想过,除了更换算法,还有哪些“大招”?这篇文章堪称典范,它将一个普通的函数,通过四套组合拳,硬生生把性能提升了330倍!作者不仅展示了“术”,更传授...
- 7 段不到 50 行的 Python 脚本,解决 7 个真实麻烦:代码、场景与可复制
-
“本文整理自开发者AbdurRahman在Stackademic的真实记录,所有代码均经过最小化删减,确保在50行内即可运行。每段脚本都对应一个日常场景,拿来即用,无需额外依赖。一、在朋...
- Python3.14:终于摆脱了GIL的限制
-
前言Python中最遭人诟病的设计之一就是GIL。GIL(全局解释器锁)是CPython的一个互斥锁,确保任何时刻只有一个线程可以执行Python字节码,这样可以避免多个线程同时操作内部数据结...
- Python Web开发实战:3小时从零搭建个人博客
-
一、为什么选Python做Web开发?Python在Web领域的优势很突出:o开发快:Django、Flask这些框架把常用功能都封装好了,不用重复写代码,能快速把想法变成能用的产品o需求多:行业...
- 图解Python编程:从入门到精通系列教程(附全套速查表)
-
引言本系列教程展开讲解Python编程语言,Python是一门开源免费、通用型的脚本编程语言,它上手简单,功能强大,它也是互联网最热门的编程语言之一。Python生态丰富,库(模块)极其丰富,这使...
- Python 并发编程实战:从基础到实战应用
-
并发编程是提升Python程序效率的关键技能,尤其在处理多任务场景时作用显著。本文将系统介绍Python中主流的并发实现方式,帮助你根据场景选择最优方案。一、多线程编程(threading)核...
- 吴恩达亲自授课,适合初学者的Python编程课程上线
-
吴恩达教授开新课了,还是亲自授课!今天,人工智能著名学者、斯坦福大学教授吴恩达在社交平台X上发帖介绍了一门新课程——AIPythonforBeginners,旨在从头开始讲授Python...
- Python GUI 编程:tkinter 初学者入门指南——Ttk 小部件
-
在本文中,将介绍Tkinter.ttk主题小部件,是常规Tkinter小部件的升级版本。Tkinter有两种小部件:经典小部件、主题小部件。Tkinter于1991年推出了经典小部件,...
- Python turtle模块编程实践教程
-
一、模块概述与核心概念1.1turtle模块简介定义:turtle是Python标准库中的2D绘图模块,基于Logo语言的海龟绘图理念实现。核心原理:坐标系系统:原点(0,0)位于画布中心X轴:向右...
- Python 中的asyncio 编程入门示例-1
-
Python的asyncio库是用于编写并发代码的,它使用async/await语法。它为编写异步程序提供了基础,通过非阻塞调用高效处理I/O密集型操作,适用于涉及网络连接、文件I/O...
- 30天学会Python,开启编程新世界
-
在当今这个数字化无处不在的时代,Python凭借其精炼的语法架构、卓越的性能以及多元化的应用领域,稳坐编程语言排行榜的前列。无论是投身于数据分析、人工智能的探索,还是Web开发的构建,亦或是自动化办公...
- Python基础知识(IO编程)
-
1.文件读写读写文件是Python语言最常见的IO操作。通过数据盘读写文件的功能都是由操作系统提供的,读写文件就是请求操作系统打开一个文件对象(通常称为文件描述符),然后,通过操作系统提供的接口从这个...
- Python零基础到精通,这8个入门技巧让你少走弯路,7天速通编程!
-
Python学习就像玩积木,从最基础的块开始,一步步搭建出复杂的作品。我记得刚开始学Python时也是一头雾水,走了不少弯路。现在回头看,其实掌握几个核心概念,就能快速入门这门编程语言。来聊聊怎么用最...
- 一文带你了解Python Socket 编程
-
大家好,我是皮皮。前言Socket又称为套接字,它是所有网络通信的基础。网络通信其实就是进程间的通信,Socket主要是使用IP地址,协议,端口号来标识一个进程。端口号的范围为0~65535(用户端口...
- Python-面向对象编程入门
-
面向对象编程是一种非常流行的编程范式(programmingparadigm),所谓编程范式就是程序设计的方法论,简单的说就是程序员对程序的认知和理解以及他们编写代码的方式。类和对象面向对象编程:把...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (77)
- python封装 (57)
- python写入txt (66)
- python读取文件夹下所有文件 (59)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)