SoFunction
Updated on 2024-11-21

Using python to merge multiple excel files into the same file

Application Scenario: Use pandas to merge multiple Excel files with the same structure into one.

Raw data:

 

Related Code:

import os
import pandas as pd


# Read the file out and put it in a list #

pwd = 'test' # Get the file directory

# New list to hold filenames
file_list = []

# Create a new list to hold the data for each file (read multiple Excel files with the same structure in turn and create a DataFrame)
dfs = []

for root,dirs,files in (pwd): # The first is the start path, the second is the folder under the start path, and the third is the file under the start path.
  for file in files:
    file_path = (root, file)
    file_list.append(file_path) # Use (dirpath, name) to get the full path
    df = pd.read_excel(file_path) # Convert excel to DataFrame
    (df)

# Merge multiple DataFrames into one
df = (dfs)

# Write to excel file without indexing data
df.to_excel('test\\', index=False)

Consolidated results:

This is the whole content of this article.