Exercise Solutions Available
Step-by-step answers for all textbook questions in this chapter
Chapter 13 — Python and CSV Files: Exercise Solutions Guide
How to Use This Page
1. Attempt every exercise in your Samacheer Kalvi textbook on your own first. 2. Compare your answers with the solutions below — focus on the method, not just the final result. 3. Practise the Python programs on a computer; copy-pasting alone will not build exam skills. 4. Review the Common Mistakes and Exam Checklist before your exam.
Key Concepts
File Modes in Python
| Mode | Description |
|---|---|
'r' | Read (default) — file must exist |
'w' | Write — creates file or overwrites existing |
'a' | Append — creates file or adds to end |
'r+' | Read and write — file must exist |
'x' | Exclusive creation — fails if file exists |
CSV Module Functions
| Function | Purpose |
|---|---|
csv.reader(file) | Returns an iterator yielding rows as lists |
csv.writer(file) | Returns a writer object for writing lists as rows |
csv.DictReader(file) | Returns rows as dictionaries (keys = header names) |
csv.DictWriter(file, fieldnames) | Writes dictionaries as rows |
The with Statement
with open("file.csv", "r") as f:
# file automatically closes when block ends
pass
Using with ensures the file is closed even if an exception occurs.
Multiple Choice Questions
Q1. Which module is imported to handle CSV files in Python?
- (a)
file  (b)csv  (c)pandas  (d)excel
Q2. What does csv.reader() return?
- (a) A dictionary   (b) A list of strings   (c) An iterator of lists   (d) A tuple
Q3. Which argument prevents extra blank lines when writing CSV on Windows?
- (a)
encoding='utf-8'  (b)newline=''  (c)delimiter=','  (d)mode='w'
Q4. csv.DictReader() reads each row as:
- (a) A list   (b) A tuple   (c) A dictionary   (d) A set
Q5. Which file mode opens a file for appending without overwriting?
- (a)
'r'  (b)'w'  (c)'a'  (d)'x'
Q6. What does writerow() do?
- (a) Reads one row   (b) Writes one row to the CSV file   (c) Deletes a row   (d) Sorts rows
Fill in the Blanks
1. The function used to open a file in Python is ______. → open() 2. The with statement ensures the file is ______ automatically after the block ends. → closed 3. csv.writer() returns a writer object that has methods ______() and writerows(). → writerow 4. In DictReader, the keys of each row dictionary come from the ______ row of the file. → header / first 5. The file mode 'w' ______ an existing file before writing. → overwrites / truncates 6. To write multiple rows at once, use the ______ method of a csv writer. → writerows()
True or False
csv module must be installed separately using pip.Match the Following
| Column A | Column B |
|---|---|
1. csv.reader() | a. Write multiple rows at once |
2. csv.writer() | b. Read rows as dictionaries |
3. csv.DictReader() | c. Read rows as lists |
4. csv.DictWriter() | d. Write rows as dictionaries |
5. writerows() | e. Write rows as lists |
Short Answer Questions
Q1. Explain file opening modes in Python.
| Mode | Description |
|---|---|
'r' | Read-only; file must exist (default) |
'w' | Write; creates new or overwrites existing |
'a' | Append; creates new or appends to end |
'r+' | Read + write; file must exist |
'x' | Exclusive create; error if file exists |
Q2. What is the with statement? Why is it preferred for file handling?
The with statement is a context manager that ensures a file is automatically closed after the block, even if an exception occurs.
# Preferred — auto close
with open("data.csv", "r") as f:
data = f.read()
# Without with — must close manually
f = open("data.csv", "r")
data = f.read()
f.close() # easy to forget
Q3. Differentiate between csv.reader() and csv.DictReader().
| Feature | csv.reader() | csv.DictReader() |
|---|---|---|
| Returns each row as | List of strings | Dictionary |
| Access columns by | Index (row[0], row[1]) | Key (row["Name"]) |
| Requires header row | No (optional) | Yes (or specify fieldnames) |
| Readability | Lower | Higher |
Q4. Write the syntax for csv.writer() and writerow().
import csv
with open("output.csv", "w", newline="") as f:
w = csv.writer(f)
w.writerow(["Name", "Age", "City"])
w.writerow(["Arun", 18, "Chennai"])
Q5. How do you read a CSV file line by line?
import csv
with open("data.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row) # row is a list like ['Arun', '18', 'Chennai']
Detailed Answer Questions
Q1. Write a Python program to create a CSV file with student details (Roll No, Name, Mark) and write 3 records.
import csv
# Data to write
students = [
["Roll No", "Name", "Mark"],
[1, "Arun", 95],
[2, "Bala", 88],
[3, "Chitra", 76]
]
# Write to CSV
with open("student.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(students)
print("student.csv created successfully.")
Output in student.csv:
Q2. Write a Python program to read a CSV file and display all rows using csv.reader().
import csv
with open("student.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
# Each row is a list of strings
print(row)
Sample output:
Q3. Write a Python program using DictReader to read a CSV file and print each row as a dictionary.
import csv
with open("student.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(row) # row is a dict: {'Roll No': '1', 'Name': 'Arun', 'Mark': '95'}
print(f"Name: {row['Name']}, Mark: {row['Mark']}")
Sample output:
Q4. Write a Python program using DictWriter to write student records to a CSV file.
import csv
fields = ["Roll No", "Name", "Mark"]
rows = [
{"Roll No": "1", "Name": "Arun", "Mark": "95"},
{"Roll No": "2", "Name": "Bala", "Mark": "88"},
{"Roll No": "3", "Name": "Chitra", "Mark": "76"}
]
with open("student_dict.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=fields)
writer.writeheader() # Write header row
writer.writerows(rows)
print("student_dict.csv created successfully.")
Q5. Write a Python program to append a new record to an existing CSV file.
import csv
new_record = [4, "Deepa", 91]
with open("student.csv", "a", newline="") as f:
writer = csv.writer(f)
writer.writerow(new_record)
print("Record appended successfully.")
# Verify by reading
with open("student.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
Q6. Write a Python program that reads a CSV file containing marks and calculates the average mark.
import csv
total = 0
count = 0
with open("student.csv", "r") as f:
reader = csv.DictReader(f) # Skip header automatically
for row in reader:
mark = int(row["Mark"])
total += mark
count += 1
if count > 0:
average = total / count
print(f"Total Marks: {total}")
print(f"Number of Students: {count}")
print(f"Average Mark: {average:.2f}")
else:
print("No student records found.")
Common Mistakes
| Mistake | Why It's Wrong | Fix |
|---|---|---|
open("file.csv", "w") without newline="" | On Windows, CSV rows get extra blank lines | Always use open("file.csv", "w", newline="") |
f.close() after a with block | The file is already closed; calling close again is harmless but unnecessary | Rely on with to close automatically |
Accessing row[2] with DictReader | DictReader returns dicts, not lists | Use row["Mark"] instead of row[2] |
Forgetting import csv | NameError: csv module not found | Always import the module first |
Using 'w' mode when you meant 'a' | 'w' overwrites the entire file; 'a' appends | Use 'a' to add data without losing existing content |
writerow(["Name", "Age"]) vs writerows([...]) | writerow writes one row; writerows writes a list of rows | Use writerow for one row, writerows for multiple |
Not converting string values from reader | csv.reader returns all values as strings | Convert with int(), float() as needed |
Exam Checklist
- [ ] Can explain file modes (
'r','w','a','r+','x') - [ ] Can write a program to create and write a CSV file using
csv.writer() - [ ] Can read a CSV file using
csv.reader()and iterate through rows - [ ] Can use
csv.DictReader()to read rows as dictionaries - [ ] Can use
csv.DictWriter()to write dictionaries to CSV - [ ] Know the difference between
writerow()andwriterows() - [ ] Understand the
withstatement and why it is preferred - [ ] Know why
newline=''is needed when writing CSV files - [ ] Can append records to an existing CSV file
- [ ] Can process CSV data (calculate totals, averages, search, filter)
