← Back to Unit 1

Week 9 Lesson 2 Teacher Solution

Teacher material

YEAR 9 DIGITAL TECHNOLOGIES • PYTHON FILES

Working with CSV Files in Python

In this lesson, you will use Python file handling and the csv module to save, read, append, and modify data in a CSV file.

CONTEXT

CSV stands for comma-separated values. It is a common file format used to store data in rows and columns.

Unlike normal variables, data saved in a file can still be used after the program closes.

In Python, this means a program can write data into a CSV file, read it back later, add new rows, and update existing rows.

Your focus in this lesson is to learn the core file operations needed to work with a file such as logbook.csv or diary.csv.

LEARNING GOALS
  1. Create a CSV file.
  2. Write rows into the file.
  3. Read rows back into Python.
  4. Append new rows to the file.
  5. Modify an existing row by reading and rewriting the file.
Lesson overview

In this lesson, you will work through the following sequence:

Stage 1: Write a CSV file
Create a file, add a header row, and write data rows into it.
Stage 2: Read CSV data
Use Python to read all rows, process rows one by one, and store rows in a list.
Stage 3: Append data
Add new rows without deleting the existing contents of the file.
Stage 4: Modify a row
Read all rows, change the required row, then write the updated data back into the file.

Important: Focus on the file handling process. Keep each program simple and make sure it completes the required task clearly.

KEY IDEAS
  • A file can store data after the program ends.
  • A CSV file stores data in rows and columns.
  • Python uses file modes such as "w", "a", and "r".
  • The csv module helps Python read and write CSV files correctly.
  • Appending adds new rows to the end of the file.
  • Modifying a row usually means reading the whole file, changing the row, and saving the whole file again.
SUCCESS CRITERIA
  • Your program can create a CSV file.
  • Your program can write rows into the file.
  • Your program can read rows back from the file.
  • Your program can append a new row without deleting old rows.
  • Your program can modify an existing row and save the changes.
  • Your code and output are clear and readable.
Python tools you will use

This lesson uses Python file handling and the built-in csv module.

Useful things to remember
  • import csv lets you use CSV tools in Python.
  • csv.writer() writes rows to a CSV file.
  • csv.reader() reads rows from a CSV file.
  • newline="" helps avoid blank lines in some systems.

Key idea: Files store data outside the program, so the data can still be used later.

Stage 1: Write a CSV file

The first step is to create a CSV file and write rows into it.

This example creates logbook.csv, writes a header row, and then writes 3 data rows.

# ============================================================
# STAGE 1: WRITE A CSV FILE
# ============================================================

import csv

filename = "logbook.csv"

with open(filename, "w", newline="") as f:
    writer = csv.writer(f)

    writer.writerow(["Entry", "Message"])
    writer.writerow([1, "Hello CSV file!"])
    writer.writerow([2, "Python can save table data."])
    writer.writerow([3, "This is row three."])

print("Done! Created/overwrote:", filename)
Stage 2: Read the CSV file

Once data is stored, you can read it back into Python.

This example reads every row and prints it to the console.

# ============================================================
# STAGE 2A: READ ALL ROWS
# ============================================================

import csv

filename = "logbook.csv"

with open(filename, "r", newline="") as f:
    reader = csv.reader(f)
    rows = list(reader)

print("=== CSV CONTENTS START ===")
for row in rows:
    print(row)
print("=== CSV CONTENTS END ===")

This example reads row-by-row and processes each row separately.

# ============================================================
# STAGE 2B: READ ROW-BY-ROW
# ============================================================

import csv

filename = "logbook.csv"

with open(filename, "r", newline="") as f:
    reader = csv.reader(f)
    for row in reader:
        print("ROW:", row)

This example reads rows into a list so you can count them or access a specific row later.

# ============================================================
# STAGE 2C: READ CSV INTO A LIST
# ============================================================

import csv

filename = "logbook.csv"

with open(filename, "r", newline="") as f:
    reader = csv.reader(f)
    rows = list(reader)

print("Number of rows:", len(rows))

if len(rows) > 1:
    print("First data row:", rows[1])
Stage 3: Append a new row

Appending adds a new row to the end of the file without deleting the existing contents.

First
Open the file in append mode.
Second
Create a CSV writer.
Third
Write the new row to the file.
Finally
Print a message to confirm the change.
# ============================================================
# STAGE 3: APPEND A NEW ROW
# ============================================================

import csv

filename = "logbook.csv"

with open(filename, "a", newline="") as f:
    writer = csv.writer(f)
    writer.writerow([4, "Appended this row later."])

print("Added a new row to:", filename)
Stage 4: Modify an existing row

To modify a row, you usually need to read the whole file, change the correct row, and then write all rows back to the file.

# ============================================================
# STAGE 4: MODIFY AN EXISTING ROW
# ============================================================

import csv

filename = "logbook.csv"

with open(filename, "r", newline="") as f:
    reader = csv.reader(f)
    rows = list(reader)

for row in rows:
    if row[0] == "2":
        row[1] = "This row has been updated."

with open(filename, "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(rows)

print("Updated row 2 in", filename)

Important: Values read from a CSV file are treated as text, so "2" is compared as a string.

Programming tips

Tip 1: Keep the file name consistent every time you open the file.

Tip 2: Use csv.writer() and csv.reader() instead of manually adding commas.

Tip 3: Be careful with file modes.

"w" overwrites the file. "a" adds to the existing file.

Tip 4: Test your file more than once so you can confirm that new rows are being added correctly.

PRACTICE TASKS
  • Create a diary.csv file and save at least 2 diary entries.
  • Write a program that reads the file and prints the number of entries.
  • Modify one entry and save the updated version of the file.
REMEMBER

This lesson is about understanding how Python works with CSV files.

Keep the code simple, use the correct file mode, and check carefully that your file contains the rows you expect.