Để đọc tất cả các tệp excel trong một thư mục, hãy sử dụng mô-đun Glob và phương thức read_csv (). Giả sử sau đây là các tệp excel của chúng tôi trong một thư mục -
Đầu tiên, hãy để chúng tôi đặt đường dẫn và lấy các tệp csv. Tệp CSV của chúng tôi nằm trong thư mục MyProject -
path = "C:\\Users\\amit_\\Desktop\\MyProject\\"
Đọc các tệp có phần mở rộng .csv từ đường dẫn trên -
filenames = glob.glob(path + "\*.csv")
Bây giờ chúng ta hãy viết một vòng lặp for để lặp lại tất cả các tệp csv, đọc và in chúng -
for file in filenames:
# reading csv files
print("\nReading file = ",file)
print(pd.read_csv(file)) Ví dụ
Sau đây là mã hoàn chỉnh -
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)) Đầu ra
Điều này 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