如何用Python合并一个文件夹中的所有excel文件
在这篇文章中,我们将看到如何将一个文件夹中的所有Excel文件合并成一个文件。
使用的库
所使用的Python库是。
- Pandas :Pandas是一个为Python编程语言开发的Python库,用于操作数据和分析数据。它被广泛用于数据科学和数据分析中。
- Glob : glob模块根据Unix Shell使用的规则,匹配所有与指定模式匹配的路径名。
使用的Excel文件
我们将使用三个Excel文件,用python将它们合并到一个文件夹中的一个Excel文件。这三个Excel文件是x1.xlsx、x2.xlsx和x3.xlsx。
一步一步实现:
- 首先,我们必须导入库和模块
# importing pandas libraries and
# glob module
import pandas as pd
import glob
- 设置存储文件的文件夹的路径。这一行代码将获取存储文件的文件夹。
# path of the folder
path = r'test'
- 使用Glob模块显示文件夹中的文件名。glob.glob( )函数将搜索给定路径中所有扩展名为.xlsx的文件。print(filenames)显示所有扩展名为xlsx的文件名。
# reading all the excel files
filenames = glob.glob(path + "\*.xlsx")
print('File names:', filenames)
- 初始化空的数据框架。数据框是python中的一个表数据结构,用于分析和处理数据。在这里,我们必须初始化一个空的数据框架,用于存储三个文件中的综合数据
# Initializing empty data frame
finalexcelsheet = pd.DataFrame()
- 逐个遍历文件夹中的所有文件。我们必须使用for循环来迭代每个文件。pd.concat()函数将把excel文件中的所有多张文件连接起来,如本例中的第三个excel文件,并存储在一个名为df的变量中。最终excelsheet.append()函数将把df变量中的数据逐一追加到最终excelsheet中。因此,通过这段代码,你将能够轻松地合并Excel文件
# to iterate excel file one by one
# inside the folder
for file in filenames:
# combining multiple excel worksheets
# into single data frames
df = pd.concat(pd.read_excel(file, sheet_name=None),
ignore_index=True, sort=False)
# Appending excel files one by one
finalexcelsheet = finalexcelsheet.append(
df, ignore_index=True)
- 显示合并后的数据。要显示合并后的文件,只要写print(finalexcelsheet)。
# to print the combined data
print('Final Sheet:')
display(finalexcelsheet)
- 将合并后的数据插入一个新的Excel文件中。
# save combined data
finalexcelsheet.to_excel(r'Final.xlsx',index=False)
下面是基于上述方法的完整python程序。
#import modules
import pandas as pd
import glob
# path of the folder
path = r'test'
# reading all the excel files
filenames = glob.glob(path + "\*.xlsx")
print('File names:', filenames)
# initializing empty data frame
finalexcelsheet = pd.DataFrame()
# to iterate excel file one by one
# inside the folder
for file in filenames:
# combining multiple excel worksheets
# into single data frames
df = pd.concat(pd.read_excel(
file, sheet_name=None), ignore_index=True, sort=False)
# appending excel files one by one
finalexcelsheet = finalexcelsheet.append(
df, ignore_index=True)
# to print the combined data
print('Final Sheet:')
display(finalexcelsheet)
finalexcelsheet.to_excel(r'Final.xlsx', index=False)
输出:
Final Excel: