किसी फ़ोल्डर में सभी एक्सेल फ़ाइलों को पढ़ने के लिए, ग्लोब मॉड्यूल और read_csv() विधि का उपयोग करें। मान लें कि एक निर्देशिका में हमारी एक्सेल फाइलें निम्नलिखित हैं -
सबसे पहले, हम पथ निर्धारित करते हैं और csv फ़ाइलें प्राप्त करते हैं। हमारी सीएसवी फाइलें MyProject फोल्डर में हैं -
path = "C:\\Users\\amit_\\Desktop\\MyProject\\"
उपरोक्त पथ से एक्सटेंशन .csv वाली फ़ाइलें पढ़ें -
filenames = glob.glob(path + "\*.csv")
आइए अब सभी 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