Python - 在 Pandas 中讀取資料夾中的所有 CSV 檔案?


要讀取資料夾中的所有 Excel 檔案,請使用 Glob 模組和 read_csv() 方法。假設資料夾中以下為我們的 Excel 檔案 -

首先,讓我們設定路徑並獲取 csv 檔案。我們的 CSV 檔案位於資料夾 MyProject 中 -

path = "C:\Users\amit_\Desktop\MyProject\"

從上述路徑讀取副檔名為 .csv 的檔案 -

filenames = glob.glob(path + "\*.csv")

現在讓我們編寫一個 for 迴圈來遍歷所有 csv 檔案,對其進行讀取並列印它們 -

for file in filenames:
   # reading csv files
   print("\nReading file = ",file)
   print(pd.read_csv(file))

示例

以下為完整程式碼 -

import pandas as pd
import glob

# getting csv files from the folder MyProject
path = "C:\Users\amit_\Desktop\MyProject\"

# read all the files with extension .csv
filenames = glob.glob(path + "\*.csv")
print('File names:', filenames)

# for loop to iterate all csv files
for file in filenames:
   # reading csv files
   print("\nReading file = ",file)
   print(pd.read_csv(file))

輸出

將產生以下輸出

File names:['C:\Users\amit_\Desktop\MyProject\Sales1.xlsx','C:\Users\amit_\Desktop\MyProject\Sales2.xlsx']

Reading file = C:\Users\amit_\Desktop\MyProject\Sales1.xlsx
          Car      Place   UnitsSold
0        Audi  Bangalore          80
1     Porsche     Mumbai         110
2  RollsRoyce       Pune         100

Reading file = C:\Users\amit_\Desktop\MyProject\Sales2.xlsx
          Car       Place   UnitsSold
0         BMW       Delhi          95
1    Mercedes   Hyderabad          80
2  Lamborgini  Chandigarh          80

更新日期:2021 年 9 月 27 日

6K+ 瀏覽量

開啟您的職業生涯

完成課程獲得認證

立即開始
廣告