要读取目录中的所有 excel 文件,请使用 Glob 模块和read_excel()方法。
假设以下是目录中的 excel 文件 -
销售1.xlsx
销售2.xlsx
首先,设置所有excel文件所在的路径。获取 excel 文件并使用 glob 读取它们 -
path = "C:\\Users\\amit_\\Desktop\\" filenames = glob.glob(path + "\*.xlsx") print('File names:', filenames)
接下来,使用 for 循环迭代并读取特定目录中的所有 excels 文件。我们也在使用read_excel()-
for file in filenames: print("Reading file = ",file) print(pd.read_excel(file))
以下是完整的代码 -
import pandas as pd import glob # getting excel files from Directory Desktop path = "C:\\Users\\amit_\\Desktop\\" # read all the files with extension .xlsx i.e. excel filenames = glob.glob(path + "\*.xlsx") print('File names:', filenames) # for loop to iterate all excel files for file in filenames: # reading excel files print("Reading file = ",file) print(pd.read_excel(file))输出结果
这将产生以下输出 -
File names:['C:\\Users\\amit_\\Desktop\\Sales1.xlsx','C:\\Users\\amit_\\Desktop\\Sales2.xlsx'] Reading file = C:\Users\amit_\Desktop\Sales1.xlsx Car Place UnitsSold 0 Audi Bangalore 80 1 Porsche Mumbai 110 2 RollsRoyce Pune 100 Reading file = C:\Users\amit_\Desktop\Sales2.xlsx Car Place UnitsSold 0 BMW Delhi 95 1 Mercedes Hyderabad 80 2 Lamborgini Chandigarh 80