用python合并相同格式表格
在之前,大家已经装好了python安装环境,现在可以直接使用各种代码啦。
这次的需求是,有一大堆格式相同的表格数据,想要合并成一个(比如你爬取的各种POI数据表)
真真python都没有的,先看这篇
0、准备文件
把你需要合并的相同样式的表格放在同一个文件夹内
1、打开软件
2、新建空白文件,复制代码并保存为合并表格.py
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 14 14:33:15 2023
@author: Joy_cxz
优快云:https://blog.youkuaiyun.com/cxz_0030115?spm=1010.2135.3001.5421
"""
import os
import pandas as pd
def merge_excel_files(folder_path, output_file):
all_data = pd.DataFrame()
# Get a list of all files in the folder with .xls and .xlsx extensions
xls_files = [file for file in os.listdir(folder_path) if file.lower().endswith(('.xls', '.xlsx'))]
for xls_file in xls_files:
file_path = os.path.join(folder_path, xls_file)
if xls_file.lower().endswith('.xlsx'):
df = pd.read_excel(file_path) # Use pandas for .xlsx files
else:
df = pd.read_excel(file_path, engine='xlrd') # Use xlrd for .xls files
all_data = all_data.append(df, ignore_index=True)
all_data.to_excel(output_file, index=False)
print("Merged data saved to", output_file)
# Example usage:
folder_path = r'E:\待表格汇总文件夹' # Replace this with the folder containing your files
output_file = r'E:\待表格汇总文件夹/merged_data.xlsx' # Replace this with the desired output file path
merge_excel_files(folder_path, output_file)
改这里就行:
然后运行