1 / 28
Python Data Persistence · Grade 8 · Chapter 8

File Handling & Simple Data

Reading and writing persistent data files (TXT, CSV), using `with open()` context managers, and implementing `try/except` exception handling.

Case Study

The Lost Game Save Data

A student built an incredible text RPG with scores, player inventories, and levels. But as soon as they closed the terminal window, ALL progress vanished because data was only stored in volatile RAM!

Solution: File Handling saves data to non-volatile SSD/Disk storage so programs remember state permanently.
Lesson Objectives

What We Will Master Today

Memory Architecture

Volatile RAM vs. Persistent Storage

Volatile RAM (Memory)

Ultra-fast read/write. Stores Python variables, lists, and dicts while program is running. Wiped completely when program ends!

Persistent Disk Storage

Slower than RAM, but retains files (.txt, .csv, .json) permanently even when power is disconnected.

Core Concept 1

Opening Files Safely: `with open()`

Always use the with context manager when handling file streams. It automatically closes the file handle when done, even if errors occur!

Unsafe Manual Approach

f = open("log.txt", "r") data = f.read() # If code crashes here, file stays open & corrupted! f.close()

Safe Context Manager

with open("log.txt", "r") as f: data = f.read() # Automatically closed here!
Core Concept 2

File Opening Modes Matrix

Read Mode (`'r'`)

Opens existing file for reading. Raises FileNotFoundError if file does not exist.

Write Mode (`'w'`)

Creates new file OR completely overwrites and wipes existing file contents!

Append Mode (`'a'`)

Creates new file OR appends new data to the very end without deleting existing lines.

Reading Methods

Reading Text: `.read()`, `.readline()`, `.readlines()`

with open("notes.txt", "r") as f: # Option 1: Read entire file into one big string content = f.read() # Option 2: Read into list of line strings # lines = f.readlines() # Option 3: Memory-efficient line-by-line loop for line in f: print(line.strip())
Writing Methods

Writing & Appending Data

# Appending audit entries to a log file with open("system_audit.log", "a") as log_file: log_file.write("USER_LOGIN: user='sara' status='SUCCESS'\n") log_file.write("PASSWORD_FAIL: user='admin' status='ALERT'\n")
Structured Data

Working with CSV Files (`csv` Module)

Comma-Separated Values (CSV) store tabular spreadsheet data in plain text format.

import csv # Reading CSV file with open("students.csv", "r") as file: reader = csv.reader(file) header = next(reader) # Skips header row ["Name", "Score"] for row in reader: print(f"Student {row[0]} scored {row[1]}")
Dictionary CSV Parsing

`csv.DictReader` & `csv.DictWriter`

Automatically map CSV rows directly into Python dictionaries using header column names!

import csv with open("users.csv", "r") as f: reader = csv.DictReader(f) for row in reader: print(f"User: {row['username']} | Role: {row['role']}")
Defensive Programming

Robust Error Handling: `try / except`

Catch runtime exceptions gracefully instead of letting your program crash in front of the user.

try: with open("missing_config.json", "r") as f: config = f.read() except FileNotFoundError: print("Warning: Config file not found. Loading defaults...") config = "{}" except IOError as e: print(f"Disk Read Error: {e}")
Exception Flow

`try / except / else / finally` Structure

TRY
Attempt code that might raise an exception.
EXCEPT
Catch and handle specific error types.
ELSE
Runs ONLY if no exception occurred.
FINALLY
Always runs regardless of success/error.
Scenario Analysis

High-Score Logging System

SYSTEM REQUIREMENTS

Build a score logger for an arcade game. System must read existing high scores from scores.csv, append new player scores, sort the top 5 scores, and handle missing CSV files gracefully on first launch.

Discussion: What file mode and try/except handlers are needed?
Spot the Mistake

3 Dangerous File Handling Bugs

Guided Practice

Analyzing User Security Logs

def count_failed_logins(filename): failed_count = 0 try: with open(filename, "r") as f: for line in f: if "FAIL" in line: failed_count += 1 return failed_count except FileNotFoundError: return -1 print(count_failed_logins("system_audit.log"))
Hands-on Challenge

Exporting Student Quiz Results to CSV

Write a script that takes a list of dictionaries and writes them to results.csv:

results = [ {"name": "Ahmad", "score": 92}, {"name": "Fatima", "score": 98} ]
Check Your Understanding

What happens if you open an existing file using mode `'w'`?

ANew text is added to the end of the file
BThe file is completely overwritten and existing content is erased
CPython raises a FileExistsError exception
DThe file becomes read-only permanently
Click to reveal answer
Check Your Understanding

Why is `with open(...) as f:` preferred over `f = open(...)`?

AIt speeds up disk read speeds by 100%
BIt automatically closes the file handle, preventing memory leaks and corruption
CIt encrypts the file automatically
DIt converts text files into CSV files
Click to reveal answer
Check Your Understanding

Which exception is raised when trying to read a non-existent file?

AKeyError
BFileNotFoundError
CZeroDivisionError
DIndexError
Click to reveal answer
Check Your Understanding

What string method strips trailing `\n` newline characters?

A.clean()
B.strip()
C.pop()
D.remove()
Click to reveal answer
Data Formats Evaluation

TXT vs. CSV vs. JSON

TXT Files

Best for unstructured plain text, raw logs, and notes.

CSV Files

Best for structured tabular spreadsheets and matrix datasets.

JSON Files

Best for complex, deeply nested hierarchical data and Web APIs.

Data Pipeline Workshop

Building a Safe File Data Importer

Write a function safe_load_csv(filepath) that reads a CSV file and returns a list of dicts, returning an empty list if the file is missing.

Chapter Summary

File Handling & Data Reference

Exit Ticket

Quick Code Challenge

Write the 3 lines of Python code required to open scores.txt in append mode and add the text "Player1: 1500\n".
Looking Ahead

Next Chapter: Mini Project Part 1

With functions, data structures, and file persistence under our belt, we begin building our major capstone project — CyberShield CLI!

Capstone Preview

What is CyberShield CLI?

A complete command-line security auditing suite that evaluates password entropy, generates hashes, and saves user logs to CSV files!