简体   繁体   中英

Reading all excel files from a directory instead of listing them individually

I made a program to merge excel files based on listing their specific file names [4] but if I want merge all files listed in a particular directory (say a folder called test on my desktop) how would I go about this?

 import pandas as pd
 import os 
 os.chdir("/users/me/desktop/test") 
 excel_names = ["/users/me/desktop/test/test1.xlsx", "/users/me/desktop/test/test2.xlsx"]
 excels = [pd.ExcelFile(name) for name in excel_names]

 frames = [pd.read_excel(x, header=None,index_col=None) for x in excels]
 frames[1:] = [df[1:] for df in frames[1:]]

 combined = pd.concat(frames)

 combined.to_excel("combine.xlsx", header=False, index=False)

根据您的特定条件,可以采取以下措施:

df = pd.concat([pd.read_excel(i, header=None, index_col=None) for i in os.listdir() if i.endswith('.xlsx')])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM