Current Affairs updated daily
KalviGavaniKalviGavani

Samacheer Kalvi 12th Computer Science Chapter 13 Python & CSV Files Exercise Solutions | KalviGavani

Complete TN Board Class 12 Computer Science Chapter 13 Python and CSV Files exercise solutions — csv module, reader, writer, DictReader, DictWriter, file modes, with statement, and worked Python examples.

Updated 13 June 20269 min read

Exercise Solutions Available

Step-by-step answers for all textbook questions in this chapter

View Solutions →

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

ModeDescription
'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

FunctionPurpose
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
Answer(b) csv — the built-in csv module handles reading and writing CSV files.

Q2. What does csv.reader() return?

  • (a) A dictionary   (b) A list of strings   (c) An iterator of lists   (d) A tuple
Answer(c) An iterator of lists — each call to next() or iteration yields one row as a list of strings.

Q3. Which argument prevents extra blank lines when writing CSV on Windows?

  • (a) encoding='utf-8'   (b) newline=''   (c) delimiter=','   (d) mode='w'
Answer(b) newline='' — prevents the OS from adding an additional \r on Windows.

Q4. csv.DictReader() reads each row as:

  • (a) A list   (b) A tuple   (c) A dictionary   (d) A set
Answer(c) A dictionary — keys come from the first row (header) or the fieldnames parameter.

Q5. Which file mode opens a file for appending without overwriting?

  • (a) 'r'   (b) 'w'   (c) 'a'   (d) 'x'
Answer(c) 'a' — append mode creates the file if it does not exist or adds data to the end.

Q6. What does writerow() do?

  • (a) Reads one row   (b) Writes one row to the CSV file   (c) Deletes a row   (d) Sorts rows
Answer(b) Writes one row — it takes a list (or dict for DictWriter) and writes it as a CSV line.

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

1. The csv module must be installed separately using pip.
AnswerFalse — it is a built-in Python module. 2. csv.reader() can only read files opened in text mode ('r'). → True — CSV is a text format; the file must be opened in text mode. 3. DictReader is more readable than reader because it uses column headers as keys. → True 4. The with statement requires an explicit f.close() at the end. → False — with automatically closes the file. 5. writerow() accepts a list; writerows() accepts a list of lists. → True 6. Opening a file in 'w' mode preserves existing content. → False — 'w' overwrites the entire file.

Match the Following

Column AColumn 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
Answer1-c, 2-e, 3-b, 4-d, 5-a

Short Answer Questions

Q1. Explain file opening modes in Python.

ModeDescription
'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().

Featurecsv.reader()csv.DictReader()
Returns each row asList of stringsDictionary
Access columns byIndex (row[0], row[1])Key (row["Name"])
Requires header rowNo (optional)Yes (or specify fieldnames)
ReadabilityLowerHigher

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:

Roll No,Name,Mark 1,Arun,95 2,Bala,88 3,Chitra,76

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:

['Roll No', 'Name', 'Mark'] ['1', 'Arun', '95'] ['2', 'Bala', '88'] ['3', 'Chitra', '76']

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:

{'Roll No': '1', 'Name': 'Arun', 'Mark': '95'} Name: Arun, Mark: 95 {'Roll No': '2', 'Name': 'Bala', 'Mark': '88'} Name: Bala, Mark: 88

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

MistakeWhy It's WrongFix
open("file.csv", "w") without newline=""On Windows, CSV rows get extra blank linesAlways use open("file.csv", "w", newline="")
f.close() after a with blockThe file is already closed; calling close again is harmless but unnecessaryRely on with to close automatically
Accessing row[2] with DictReaderDictReader returns dicts, not listsUse row["Mark"] instead of row[2]
Forgetting import csvNameError: csv module not foundAlways import the module first
Using 'w' mode when you meant 'a''w' overwrites the entire file; 'a' appendsUse 'a' to add data without losing existing content
writerow(["Name", "Age"]) vs writerows([...])writerow writes one row; writerows writes a list of rowsUse writerow for one row, writerows for multiple
Not converting string values from readercsv.reader returns all values as stringsConvert 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() and writerows()
  • [ ] Understand the with statement 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)

Frequently Asked Questions

The built-in csv module provides csv.reader(), csv.writer(), csv.DictReader(), and csv.DictWriter() for reading and writing CSV files.