Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách đọc tất cả file excel trong thư mục làm DataFrame Pandas

Để đọc tất cả file excel trong thư mục, sử dụng module Glob và phương thức read_excel().

Giả sử các file excel của chúng ta trong thư mục như sau:

Sales1.xlsx

Cách đọc tất cả file excel trong thư mục làm DataFrame Pandas

Sales2.xlsx

Cách đọc tất cả file excel trong thư mục làm DataFrame Pandas

Trước tiên, đặt đường dẫn nơi chứa tất cả file excel. Lấy file excel và đọc chúng dùng glob:

path = "C:\\Users\\amit_\\Desktop\\"
filenames = glob.glob(path + "\\*.xlsx")
print('File names:', filenames)

Tiếp theo, dùng vòng lặp for để lặp và đọc tất cả file excel trong thư mục cụ thể. Chúng ta cũng dùng read_excel():

for file in filenames:
    print("Đang đọc file = ", file)
    print(pd.read_excel(file))

Ví dụ hoàn chỉnh

Mã nguồn đầy đủ:

import pandas as pd
import glob
# lấy file excel từ thư mục Desktop
path = "C:\\Users\\amit_\\Desktop\\"
# đọc tất cả file với đuôi .xlsx tức là excel
filenames = glob.glob(path + "\\*.xlsx")
print('File names:', filenames)
# vòng lặp for lặp qua tất cả file excel
for file in filenames:
    # đọc file excel
    print("Đang đọc file = ", file)
    print(pd.read_excel(file))

Kết quả

Chương trình sẽ tạo ra kết quả sau:

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