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

Source: https://ravindrabagale.com/mr/datascience/py09-how-to-read-and-write-csv-json-and-text-files-in-python/p9-3-how-to-read-a-csv-file-in-python-with-the-csv.html
Language: mr (Marathi with English technical terms)

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

बहुतेक 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 मध्ये बदला.

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

Input file sales.csv:

```text
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
```

```python
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:

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

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

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

Input file sales.csv:

```text
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
```

```python
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:

```text
Total revenue: ₹612.00
```

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

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

Input file sales.csv:

```text
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
```

```python
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:

```text
Pune 252.0
Mumbai 80.0
Nagpur 280.0
```

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

रवींद्र बागले यांची tip

pandas file विचित्रपणे वाचत असेल तर साध्या Python ने उघडून पहिल्या 3 lines print करा. खरा separator आणि header दिसेल.
