转载:How to Consolidate Multiple Excel Workbooks With Python
想要将同一文件夹下xlsx文件合并为一个文件:
代码:代码来源(仅供学习)
import pandas as pd
import os
input_file_path = "./excel/"
output_file_path = "./excel/"
#create a list to store all the file references of the input folder using the listdir function from the os library.
#To see the contents of a library (like the listdir function, you can use the dir function on the library name).
#Use dir(library_name) to list contents
excel_file_list = os.listdir(input_file_path)
#create a new, blank dataframe, to handle the excel file imports
df = pd.DataFrame()
#Run a for loop to loop through each file in the list
for excel_files in excel_file_list:
#check for .xlsx suffix files only
if excel_files.endswith(".xlsx"):
#create a new dataframe to read/open each Excel file from the list of files created above
df1 = pd.read_excel(input_file_path+excel_files)
#append each file into the original empty dataframe
df = df.append(df1)
#transfer final output to an Excel (xlsx) file on the output path
df.to_excel(output_file_path+"merge.xlsx",index=None)
print('done!')