Skip to content
Computer Science · Grade 11 · Data Structures and Management · Term 3

Data Persistence: File I/O

Learn to read from and write to files, understanding different file formats (text, CSV) and error handling.

Ontario Curriculum ExpectationsCS.HS.D.5CS.HS.P.5

About This Topic

Data persistence through file input/output lets programs store and retrieve information beyond a single run. Grade 11 students learn to read text files line by line, parse CSV data with modules like csv, and write processed results to new files. They handle errors such as FileNotFoundError or permission issues using try-except blocks. This directly supports curriculum standards on data management and prepares students for real applications like logging or data export.

In the Data Structures and Management unit, file I/O builds on lists and dictionaries by showing how to serialize data externally. Students compare text files, which are human-readable and portable, to databases, which handle large-scale queries but require servers. Programs that read CSV sales data, compute totals, and output summaries answer key questions on error handling and storage trade-offs.

Active learning excels with file I/O because students get instant feedback from code execution. Pair debugging of faulty file operations or group challenges to build data pipelines turn abstract persistence into concrete skills, boosting problem-solving confidence and long-term retention.

Key Questions

  1. Explain the importance of error handling when performing file input/output operations.
  2. Compare the advantages and disadvantages of storing data in text files versus a database.
  3. Construct a program that reads data from a CSV file, processes it, and writes it to another file.

Learning Objectives

  • Analyze the potential consequences of file access errors, such as data corruption or program crashes, by explaining specific error handling scenarios.
  • Compare and contrast the trade-offs between using plain text files and CSV files for data storage, considering factors like readability, structure, and ease of parsing.
  • Create a Python program that reads data from a specified CSV file, performs a calculation (e.g., summing values, finding averages), and writes the processed results to a new text file.
  • Evaluate the suitability of different file storage methods (text file, CSV, database) for given data management tasks, justifying choices based on project requirements.

Before You Start

Basic Programming Constructs (Variables, Data Types, Operators)

Why: Students need to understand how to store and manipulate data before they can learn to persist it.

Lists and Dictionaries

Why: File I/O often involves reading data into these structures for processing and writing processed data back out.

Control Flow (If Statements, Loops)

Why: Students will use loops to read files line by line or record by record, and if statements for conditional processing or error checking.

Key Vocabulary

File I/OInput/Output operations that involve reading data from or writing data to a file on a computer's storage.
CSV (Comma Separated Values)A common file format for storing tabular data, where each line represents a record and values within a record are separated by commas.
Error HandlingThe process of anticipating and managing potential errors or exceptions that may occur during program execution, such as when a file cannot be found or accessed.
SerializationThe process of converting an object or data structure into a format that can be stored or transmitted, and reconstructed later. File I/O is a form of serialization.
FileNotFoundErrorA specific type of exception raised when a program attempts to access a file that does not exist at the specified location.

Watch Out for These Misconceptions

Common MisconceptionFiles always open successfully without checks.

What to Teach Instead

Live demos crash code on missing files, then pairs add try-except to rescue it. This reveals runtime failures early and shows how handling prevents program halts, building cautious coding habits.

Common MisconceptionText files work for all data volumes like databases.

What to Teach Instead

Group tasks overload text files with large CSVs, timing parses vs mock database queries. Discussions highlight scalability limits, clarifying when files suffice and active trials expose performance gaps.

Common MisconceptionForgetting to close files has no impact.

What to Teach Instead

Simulate leaks in extended runs where groups monitor resource use. Debriefs connect to real leaks causing crashes, with hands-on fixes emphasizing with statements for automatic closure.

Active Learning Ideas

See all activities

Real-World Connections

  • Software developers at financial institutions write programs to read transaction data from CSV files, calculate daily summaries, and log these reports for auditing purposes, ensuring data integrity and compliance.
  • Data analysts at e-commerce companies use Python scripts to read customer order histories from CSV files, analyze purchasing patterns, and export aggregated insights into new text files for marketing campaigns.
  • Game developers store game settings and player progress in text or configuration files, reading and writing data to ensure that game states are saved between play sessions.

Assessment Ideas

Exit Ticket

Provide students with a small, pre-made CSV file. Ask them to write pseudocode or a short Python snippet that reads the file, calculates the average of a specific column, and prints the result. Include a prompt: 'What is one potential error that could occur, and how would you handle it?'

Quick Check

Display a code snippet that attempts to read from a non-existent file without error handling. Ask students: 'What will happen when this code runs? What keyword or structure should be added to prevent a crash?'

Discussion Prompt

Pose the question: 'Imagine you have a large dataset of student grades. Would you store this in a simple text file, a CSV file, or a database? Explain your reasoning, considering factors like ease of access, potential for errors, and scalability.'

Frequently Asked Questions

How can active learning help students master file I/O?
Pair programming and error hunts provide immediate feedback as students run code, fix crashes, and share solutions. These approaches make error handling tangible, unlike lectures. Groups building pipelines connect reading, processing, and writing, reinforcing persistence while collaborative debugging cuts frustration and deepens understanding of real-world reliability.
What are advantages of text files over databases?
Text and CSV files offer simplicity, no setup, and portability across systems, ideal for small datasets or logs. Students edit them directly in notepads. Databases excel in speed for queries and multi-user access but need servers. Hands-on conversions from CSV to mock databases highlight trade-offs in curriculum projects.
Why is error handling critical in file I/O?
Errors like missing files or write permissions crash programs unexpectedly, frustrating users. Try-except blocks catch issues gracefully, logging details or prompting retries. In Ontario CS, students build robust code by testing edge cases, ensuring apps handle real scenarios like network drives or user deletions reliably.
How to parse CSV files effectively in Python?
Use the csv module's reader for robust handling of quotes and escapes, avoiding manual string splits that fail on commas in data. DictReader maps columns to keys for easy access. Practice with sample sales CSVs: read rows into lists of dicts, process, then writerows to output, catching ValueError on bad formats.