🧠 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:
🟢 CSV files are widely used in data analysis, databases, and spreadsheets (e.g., Excel, Google Sheets).
🔧 Importing the CSV Module
📝 Writing to a CSV File
🔹 Using writer:
✅ 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:
Each row is returned as a list of values (all strings).
🔄 Writing Using DictWriter
📖 Reading Using DictReader
🔹 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.):
⚠️ Important Notes:
-
CSV values are always strings; use
int()orfloat()to convert when needed. - Avoid mixing
readerandDictReaderin the same file handling block. - Don't forget
newline=""when writing.
💡 Example Programs
🔹 Program 1: Count total number of records in a CSV file
🔹 Program 2: Display students who scored more than 80
❓ Practice Questions
📘 1 Mark – Objective:
- Which Python module is used for handling CSV files?
- Which method writes a row to a CSV file?
- What does
DictReader()return?
✍️ 2 Marks – Short Answer:
-
Differentiate between
writerow()andDictWriter.writerow(). - Why is
newline=""used in writing CSV files?
💻 3 Marks – Programming:
- Write a program to read a CSV file and print names of students scoring below 60.
- 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 andDictWriter.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.