简体   繁体   English

从目录中读取所有Excel文件,而不是单独列出它们

[英]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? 我制作了一个程序来根据列出的特定文件名来合并excel文件[4],但是如果我要合并在特定目录(例如,在我的桌面上称为test的文件夹)中列出的所有文件,我将如何处理?

 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')])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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