Class 12 Computer Science - CSV Notes
1. What is CSV?
CSV stands for Comma Separated Values. It is a file format used to store tabular data. Each row
represents a record, and columns are separated by commas.
RollNo Name Marks
1 Arjun 85
2 Meera 90
3 Rahul 78
2. Why CSV?
- Lightweight and portable.
- Can be opened in Excel, Notepad, Google Sheets, etc.
- Common for data exchange between applications.
3. Working with CSV in Python
a) Writing to CSV:
import csv
with open("[Link]", "w", newline="") as f:
writer = [Link](f)
[Link](["RollNo", "Name", "Marks"])
[Link]([1, "Arjun", 85])
[Link]([2, "Meera", 90])
[Link]([3, "Rahul", 78])
b) Reading from CSV:
import csv
with open("[Link]", "r") as f:
reader = [Link](f)
for row in reader:
print(row)
c) Using DictReader and DictWriter:
import csv
with open("[Link]", "w", newline="") as f:
fieldnames = ["RollNo", "Name", "Marks"]
writer = [Link](f, fieldnames=fieldnames)
[Link]()
[Link]({"RollNo":1, "Name":"Arjun", "Marks":85})
[Link]({"RollNo":2, "Name":"Meera", "Marks":90})
with open("[Link]", "r") as f:
reader = [Link](f)
for row in reader:
print(row["Name"], row["Marks"])
4. Common Exam Questions
- What is a CSV file? Give an example.
- Difference between reader() and DictReader().
- Write a Python program to store 5 student records in a CSV file.
- Write a program to read and display records from a CSV file.
- How is CSV different from a text file?