Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🐍 Week 1 – Data Science के लिए Python  ·  दिन 06

दिन 6: Files, CSV, JSON, Errors और Modules

⏱ 2 hours📶 Beginner🎯 100% self-study
दिन 6 / 60

✅ आज आप सीखेंगे

  • with open से text files सुरक्षित पढ़ना-लिखना
  • csv module से CSV files process करना
  • JSON पढ़ना-लिखना – APIs की भाषा
  • try / except / finally से ख़राब data संभालना
  • Modules: math, statistics, datetime, random, os

🏢 असली दुनिया में

हर रात दुकान दिन के bills CSV में export करती है, और payment gateway JSON file भेजता है। दोनों पढ़ने वाली, टूटी rows पर crash होने की जगह उन्हें छोड़ने वाली और summary लिखने वाली छोटी Python script junior analysts का बहुत आम पहला काम है।

Text files

Python
with open("notes.txt", "w", encoding="utf-8") as f:     # w = write (new file)
    f.write("Day 6 – files and errors\n")
    f.write("Data science needs clean files.\n")
with open("notes.txt", "a", encoding="utf-8") as f:     # a = append
    f.write("Line added later.\n")
with open("notes.txt", encoding="utf-8") as f:          # default r = read
    for n, line in enumerate(f, 1):
        print(n, line.strip())
1 Day 6 – files and errors 2 Data science needs clean files. 3 Line added later.
💡 “with” क्यों?

with open(...) error आने पर भी file अपने आप बंद करता है। हमेशा encoding="utf-8" लिखें ताकि Hindi और ₹ symbols सही save हों।

csv module से CSV files

Python
import csv
rows = [["bill_no", "item", "qty", "price"],
        [1, "Tea 1kg", 2, 520], [2, "Atta 10kg", 1, 459], [3, "Earbuds", 1, "1,499"],
        [4, "Pen Set", "two", 150], [5, "Bedsheet", 3, 699]]
with open("bills.csv", "w", newline="", encoding="utf-8") as f:
    csv.writer(f).writerows(rows)
print(open("bills.csv", encoding="utf-8").read())
bill_no,item,qty,price 1,Tea 1kg,2,520 2,Atta 10kg,1,459 3,Earbuds,1,"1,499" 4,Pen Set,two,150 5,Bedsheet,3,699
Python
import csv
total, bad = 0, []
with open("bills.csv", encoding="utf-8") as f:
    for row in csv.DictReader(f):                 # each row is a dict
        try:
            qty = int(row["qty"])
            price = float(row["price"].replace(",", ""))
            total += qty * price
        except ValueError:
            bad.append(row["bill_no"])
print("Total sales: ₹", total)
print("Rows skipped (bad data):", bad)
Total sales: ₹ 5095.0 Rows skipped (bad data): ['4']

JSON – APIs का data

Python
import json
payments = [{"txn": "T1", "mode": "UPI", "amount": 520.0, "ok": True},
            {"txn": "T2", "mode": "Card", "amount": 1499.0, "ok": False},
            {"txn": "T3", "mode": "UPI", "amount": 459.0, "ok": True}]
with open("payments.json", "w", encoding="utf-8") as f:
    json.dump(payments, f, indent=2)
with open("payments.json", encoding="utf-8") as f:
    data = json.load(f)
success = [p for p in data if p["ok"]]
print("Successful:", len(success), "| Amount: ₹", sum(p["amount"] for p in success))
print(json.dumps(data[1]))                 # dict -> JSON text
Successful: 2 | Amount: ₹ 979.0 {"txn": "T2", "mode": "Card", "amount": 1499.0, "ok": false}
PythonJSON
dictobject { }
listarray [ ]
strstring
int / floatnumber
True / Falsetrue / false
Nonenull

Errors और exceptions

🔤
ValueErrorint("two") – ग़लत value
➗
ZeroDivisionErrorख़ाली list का average
🔑
KeyErrorcolumn न हो तब row["phone"]
📁
FileNotFoundErrorग़लत path या नाम
Data के काम में सबसे ज़्यादा दिखने वाली errors
Python
def safe_average(values):
    try:
        avg = sum(values) / len(values)
    except ZeroDivisionError:
        print("No values – returning 0")
        return 0
    except TypeError as e:
        print("Bad value in list:", e)
        return None
    else:
        return round(avg, 2)          # runs only if no error
    finally:
        print("checked", values)      # always runs

print(safe_average([10, 20, 35]))
print(safe_average([]))
print(safe_average([10, "x"]))
checked [10, 20, 35] 21.67 No values – returning 0 checked [] 0 Bad value in list: unsupported operand type(s) for +: 'int' and 'str' checked [10, 'x'] None
Python
def check_age(age):
    if not 0 < age < 120:
        raise ValueError(f"Impossible age: {age}")
    return age

for a in [25, 150]:
    try:
        print("OK", check_age(a))
    except ValueError as e:
        print("Rejected ->", e)
OK 25 Rejected -> Impossible age: 150

काम के built-in modules

Python
import math, statistics as st, random
from datetime import date, datetime, timedelta
print(math.sqrt(144), math.ceil(4.2), math.floor(4.8), round(math.pi, 4))
marks = [56, 78, 91, 45, 88, 67, 78]
print("mean", round(st.mean(marks), 2), "| median", st.median(marks), "| mode", st.mode(marks))
random.seed(1)                                # same "random" result every run
print("Lucky draw:", random.choice(["Aman", "Priya", "Rahul", "Sneha"]), random.sample(range(1, 50), 3))
d = date(2024, 10, 31)
print(d.strftime("%d %b %Y, %A"), "| +45 days:", d + timedelta(days=45))
print(datetime.strptime("15/08/2024", "%d/%m/%Y").year)
12.0 5 4 3.1416 mean 71.86 | median 78 | mode 78 Lucky draw: Priya [37, 49, 5] 31 Oct 2024, Thursday | +45 days: 2024-12-15 2024
Python
import os
print("Current folder has CSV files:", sorted(f for f in os.listdir(".") if f.endswith(".csv"))[:4])
print("bills.csv exists:", os.path.exists("bills.csv"), "| size:", os.path.getsize("bills.csv"), "bytes")
os.makedirs("reports", exist_ok=True)
print(os.path.join("reports", "summary.txt"))
Current folder has CSV files: ['ab_test.csv', 'bills.csv', 'delhi_weather.csv', 'departments.csv'] bills.csv exists: True | size: 118 bytes reports/summary.txt

अपना module

Python
code = 'def gst(amount, rate=18):\n    return round(amount * rate / 100, 2)\n'
with open("mytools.py", "w") as f:       # normally you create this file in an editor
    f.write(code)
import mytools
print(mytools.gst(1499), mytools.gst(459, rate=5))
269.82 22.95

असली example: रात की sales report

Python
import csv, json
from datetime import date
summary = {"date": str(date(2024, 11, 1)), "bills": 0, "revenue": 0.0, "skipped": 0}
with open("bills.csv", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        try:
            summary["revenue"] += int(row["qty"]) * float(row["price"].replace(",", ""))
            summary["bills"] += 1
        except ValueError:
            summary["skipped"] += 1
with open("reports/daily_summary.json", "w") as f:
    json.dump(summary, f, indent=2)
print(open("reports/daily_summary.json").read())
{ "date": "2024-11-01", "bills": 4, "revenue": 5095.0, "skipped": 1 }

🏅 आज के Job Skills

✔ Text, CSV और JSON पढ़ना-लिखना✔ Crash की जगह ख़राब rows छोड़ना✔ असंभव data पर साफ़ errors देना✔ math, statistics, datetime, random और os इस्तेमाल करना

Practice tasks

🏋️ Practice – ख़ुद करें

Task 1: 5 students के name और marks वाली marks.csv लिखें, फिर पढ़कर class average print करें।
Solution देखें
Python
import csv
data = [["name", "marks"], ["Aman", 78], ["Priya", 95], ["Rahul", 52], ["Sneha", 81], ["Kabir", 67]]
with open("marks.csv", "w", newline="") as f:
    csv.writer(f).writerows(data)
with open("marks.csv") as f:
    m = [int(r["marks"]) for r in csv.DictReader(f)]
print("Average:", sum(m) / len(m))
Average: 74.6
Task 2: तीन products और prices वाली JSON string से सबसे सस्ते product का नाम print करें।
Solution देखें
Python
import json
text = '[{"name": "Pen", "price": 20}, {"name": "Bag", "price": 899}, {"name": "Eraser", "price": 5}]'
items = json.loads(text)
print(min(items, key=lambda p: p["price"])["name"])
Eraser
Task 3: 1 Jan 2025 से 31 Mar 2025 (financial-year end) तक कितने दिन हैं? datetime इस्तेमाल करें।
Solution देखें
Python
from datetime import date
print((date(2025, 3, 31) - date(2025, 1, 1)).days, "days")
89 days

Quick quiz

🧠 Quick Quiz – ख़ुद को जाँचें

1. कौन सा mode मौजूदा file के अंत में text जोड़ता है?
"a" मतलब append; "w" पहले file मिटा देगा।
2. csv.DictReader हर row को किस रूप में देता है?
Keys header के नाम होते हैं।
3. JSON null Python में क्या बनता है?
null ↔ None।
4. finally block कब चलता है?
finally हमेशा चलता है – cleanup के लिए अच्छा।
5. random.seed(1) किसलिए?
Fixed seed हर बार वही random numbers देता है – reproducible data science के लिए ज़रूरी।

Interview corner

💼 Interview Corner

Memory में न आने वाली 5 GB CSV कैसे process करेंगे?

इसे chunks में पढ़ें – csv module से line-by-line, या pandas में pd.read_csv(..., chunksize=100000) – हर chunk aggregate करके results जोड़ें। सिर्फ़ ज़रूरी columns load करें।

Bare except की जगह specific exceptions क्यों पकड़ें?

Bare except असली bugs (typos और KeyboardInterrupt तक) छुपा देता है। ValueError या KeyError पकड़ना सिर्फ़ अपेक्षित ख़राब data संभालता है और बाकी problems सामने आने देता है।

सारांश

  • with open(..., encoding="utf-8") files सुरक्षित पढ़ता-लिखता है।
  • csv.DictReader + try/except बिखरी CSVs बिना crash के process करते हैं।
  • json.dump / json.load APIs और files से data लाते-ले जाते हैं।
  • statistics, datetime और os जैसे modules code लिखना बचाते हैं।
➡️ आगे

Day 7: पूरे हफ़्ते को mini project में जोड़ें – pure Python में personal expense analyzer।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

csv module या pandas?
छोटी scripts और row-by-row पढ़ी जाने वाली बड़ी files के लिए csv ठीक है। Analysis के लिए pandas (Day 10 से) कहीं आसान और तेज़ है।
CSV लिखते समय newline="" क्यों?
यह Windows पर rows के बीच ख़ाली lines आने से रोकता है।
json.load और json.loads में क्या फ़र्क है?
load file object से पढ़ता है; loads (load string) JSON text string parse करता है।
← Data Science (60 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

अगला topicदिन 7: Mini Project: Expense Analyzer आपकी प्रगति: 6 / 60 (10%) · Lesson 7 / 60 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें