Python合并多个Excel文件

2025-11-09 19:01:53

1、导入包

import os

import pandas as pd

import openpyxl

import warnings

warnings.filterwarnings("ignore")

Python合并多个Excel文件

2、添加源文件地址,获取文件名

dir = "./源文件"

filenames = os.listdir(dir) 

print(filenames)

Python合并多个Excel文件

Python合并多个Excel文件

3、新增空list,遍历文件append到空列

dfs = []

df1 = []

for name in filenames:

    print(name)

    df1 = pd.read_excel(os.path.join(dir, name))

    username = name

    df1['文件名'] = username

    dfs.append(df1)

Python合并多个Excel文件

4、合并文件名列,表示数据来源,后保存合并后的文件

df = pd.concat(dfs,ignore_index=True)

df.to_excel('./合并文件.xlsx', index=False)

Python合并多个Excel文件

Python合并多个Excel文件

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢