如何將目錄下的所有 Excel 檔案讀取為 Pandas DataFrame?
若要讀取目錄中的所有 Excel 檔案,請使用 Glob 模組和 read_excel() 方法。
假設目錄中包含以下 Excel 檔案 −
Sales1.xlsx
Sales2.xlsx
首先,設定包含所有 Excel 檔案的路徑。獲取 Excel 檔案並使用 glob 讀取它們 −
path = "C:\Users\amit_\Desktop\" filenames = glob.glob(path + "\*.xlsx") print('File names:', filenames)
接下來,使用 for 迴圈迭代並在特定目錄中讀取所有 Excel 檔案。我們還在使用 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
廣告