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

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

P13.2 Python Project 2: CSV File मधून Bank Statement Summary

By Ravindra Bagale

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

Files, conversion आणि dictionaries एकत्र वापरायचा खरा project.

हे काय आहे?

Statement CSV वाचून credits, debits, शेवटचा balance आणि category नुसार खर्च काढू.

कसं करायचं?

Step 1. csv.DictReader ने वाचा.

Step 2. Amount float मध्ये बदला.

Step 3. Type आणि category नुसार totals.

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

उदाहरण A: वाचा आणि summary काढा

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

date,description,category,amount
2026-03-01,Salary,income,85000
2026-03-02,Rent,housing,-25000
2026-03-05,Groceries,food,-4200
2026-03-09,Electricity,bills,-1850
2026-03-12,Restaurant,food,-1600
2026-03-20,Bad row,food,abc

हा code चालवा:

import csv
income = spend = 0
by_cat = {}
bad = 0
with open("statement.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        try:
            amt = float(row["amount"])
        except ValueError:
            bad += 1
            continue
        if amt > 0:
            income += amt
        else:
            spend += -amt
            by_cat[row["category"]] = by_cat.get(row["category"], 0) + -amt
print(f"Income: ₹{income:,.0f}  Spending: ₹{spend:,.0f}  Saved: ₹{income - spend:,.0f}")
for cat, amt in sorted(by_cat.items(), key=lambda kv: kv[1], reverse=True):
    print(f"  {cat:<8} ₹{amt:,.0f}")
print("Bad rows skipped:", bad)

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

Income: ₹85,000  Spending: ₹32,650  Saved: ₹52,350
  housing  ₹25,000
  food     ₹5,800
  bills    ₹1,850
Bad rows skipped: 1

याचा अर्थ: एकूण credit, debit आणि category नुसार खर्च मिळाला.