Để đọc tất cả file excel trong thư mục, sử dụng module Glob và phương thức read_csv(). Giả sử các file excel của chúng ta trong thư mục như sau:
Trước tiên, đặt đường dẫn và lấy file csv. File CSV nằm trong thư mục MyProject:
path = "C:\\Users\\amit_\\Desktop\\MyProject\\"
Đọc file với đuôi .csv từ đường dẫn trên:
filenames = glob.glob(path + "\\*.csv")
Viết vòng lặp for để lặp qua tất cả file csv, đọc và in ra:
for file in filenames:
# đọc file csv
print("\nĐang đọc file = ", file)
print(pd.read_csv(file))
Ví dụ hoàn chỉnh
Mã nguồn đầy đủ:
import pandas as pd
import glob
# lấy file csv từ thư mục MyProject
path = "C:\\Users\\amit_\\Desktop\\MyProject\\"
# đọc tất cả file với đuôi .csv
filenames = glob.glob(path + "\\*.csv")
print('Tên file:', filenames)
# vòng lặp for lặp qua tất cả file csv
for file in filenames:
# đọc file csv
print("\nĐang đọc file = ", file)
print(pd.read_csv(file))
Kết quả
Chương trình sẽ tạo ra kết quả sau:
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