12.6 📊 CSV File Handling in Python – Simplified for CBSE Class XII

 

🧠 What is a CSV File?

A CSV (Comma-Separated Values) file is a plain text file where each line represents a record, and commas separate the fields.

Example:

RollNo,Name,Marks 101,Ravi,89 102,Anu,92 103,Sam,75

🟢 CSV files are widely used in data analysis, databases, and spreadsheets (e.g., Excel, Google Sheets).


🔧 Importing the CSV Module

import csv

📝 Writing to a CSV File

🔹 Using writer:

import csv with open("students.csv", "w", newline="") as f: w = csv.writer(f) w.writerow(["RollNo", "Name", "Marks"]) # Header w.writerow([101, "Ravi", 89]) w.writerow([102, "Anu", 92])

newline="" avoids inserting extra blank lines in Windows.
writerow() writes one row at a time as a list.


📖 Reading from a CSV File

🔹 Using reader:

import csv with open("students.csv", "r") as f: r = csv.reader(f) for row in r: print(row)

Each row is returned as a list of values (all strings).


🔄 Writing Using DictWriter

import csv with open("students.csv", "w", newline="") as f: fieldnames = ["RollNo", "Name", "Marks"] writer = csv.DictWriter(f, fieldnames=fieldnames) writer.writeheader() writer.writerow({"RollNo": 101, "Name": "Ravi", "Marks": 89})

📖 Reading Using DictReader

import csv with open("students.csv", "r") as f: reader = csv.DictReader(f) for row in reader: print(row["Name"], "->", row["Marks"])

🔹 DictReader automatically uses the first row as field names and returns each row as a dictionary.


🔀 Custom Delimiters

To use a custom delimiter (like |, ;, etc.):

csv.writer(f, delimiter='|') csv.reader(f, delimiter='|')

⚠️ Important Notes:

  • CSV values are always strings; use int() or float() to convert when needed.
  • Avoid mixing reader and DictReader in the same file handling block.
  • Don't forget newline="" when writing.


💡 Example Programs

🔹 Program 1: Count total number of records in a CSV file

import csv with open("students.csv", "r") as f: r = csv.reader(f) next(r) # Skip header count = sum(1 for row in r) print("Total records:", count)

🔹 Program 2: Display students who scored more than 80

import csv with open("students.csv", "r") as f: r = csv.DictReader(f) for row in r: if int(row["Marks"]) > 80: print(row["Name"])

❓ Practice Questions

📘 1 Mark – Objective:

  1. Which Python module is used for handling CSV files?
  2. Which method writes a row to a CSV file?
  3. What does DictReader() return?

✍️ 2 Marks – Short Answer:

  1. Differentiate between writerow() and DictWriter.writerow().
  2. Why is newline="" used in writing CSV files?

💻 3 Marks – Programming:

  1. Write a program to read a CSV file and print names of students scoring below 60.
  2. Write a program to add 3 new records to an existing CSV file using DictWriter.

🧠 5 Marks – Case-Based:

You are given a CSV file employee.csv with fields: EmpID,Name,Salary. Write a program to:

  • Read the data using DictReader
  • Display all employee names earning more than ₹50,000
  • Count how many employees earn less than ₹30,000


🎯 Tips to Remember:

  • Always convert values before performing numeric operations (int(), float()).
  • Use writerow() with lists and DictWriter.writerow() with dictionaries.
  • Skip the header using next(reader) if needed.


✅ Conclusion

CSV File Handling is extremely useful and scoring for CBSE Class XII students. It's the most industry-relevant format among the three file types — and mastering it opens doors to data handling, analysis, and database operations.

Previous Post Next Post