Ravindra Bagale · Data Scienceसर्व coursesया course चे lessonsशोधाEnglish

Data Science · मराठी आवृत्ती · Python basics

P9.3 csv Module ने Python मध्ये CSV File कशी वाचायची?

By Ravindra Bagale

हे का शिकायचं?

बहुतेक business data CSV मध्ये येतो. pandas आधी हे साध्या Python ने समजून घ्या.

हे काय आहे?

csv.DictReader प्रत्येक row dictionary म्हणून देतो; keys म्हणजे header. सगळ्या values text असतात, गणितासाठी convert करा.

कसं करायचं?

Step 1. File उघडा (newline="").

Step 2. csv.DictReader वापरा.

Step 3. Values int/float मध्ये बदला.

उदाहरणं: copy करा आणि चालवा

उदाहरण A: Rows dictionaries म्हणून वाचा

आधी त्याच folder मध्ये sales.csv ही input file तयार करा:

date,store,item,qty,price
2026-03-01,Pune,Milk,3,56
2026-03-01,Mumbai,Bread,2,40
2026-03-02,Pune,Eggs,1,84
2026-03-02,Nagpur,Milk,5,56

हा code चालवा:

import csv
with open("sales.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        print(row["store"], row["item"], row["qty"])

तुम्हाला दिसणारा output:

Pune Milk 3
Mumbai Bread 2
Pune Eggs 1
Nagpur Milk 5

याचा अर्थ: प्रत्येक row column नावांसह dictionary झाली.

उदाहरण B: प्रत्येक row ची revenue आणि total

आधी त्याच folder मध्ये sales.csv ही input file तयार करा:

date,store,item,qty,price
2026-03-01,Pune,Milk,3,56
2026-03-01,Mumbai,Bread,2,40
2026-03-02,Pune,Eggs,1,84
2026-03-02,Nagpur,Milk,5,56

हा code चालवा:

import csv
total = 0
with open("sales.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        revenue = int(row["qty"]) * float(row["price"])
        total += revenue
print(f"Total revenue: ₹{total:,.2f}")

तुम्हाला दिसणारा output:

Total revenue: ₹612.00

याचा अर्थ: qty × price ने revenue काढली आणि बेरीज केली.

उदाहरण C: Store नुसार revenue

आधी त्याच folder मध्ये sales.csv ही input file तयार करा:

date,store,item,qty,price
2026-03-01,Pune,Milk,3,56
2026-03-01,Mumbai,Bread,2,40
2026-03-02,Pune,Eggs,1,84
2026-03-02,Nagpur,Milk,5,56

हा code चालवा:

import csv
by_store = {}
with open("sales.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        rev = int(row["qty"]) * float(row["price"])
        by_store[row["store"]] = by_store.get(row["store"], 0) + rev
for store, rev in by_store.items():
    print(store, rev)

तुम्हाला दिसणारा output:

Pune 252.0
Mumbai 80.0
Nagpur 280.0

याचा अर्थ: Dictionary मध्ये store नुसार totals जमा केले.