/en-tutor-prep-s5-ict-file-handling-exceptions/
/en-tutor-prep-s5-ict-file-handling-exceptions/
英文版
3
General Inquiry: info@TutorZone.com.hk
Office Hours: Monday to Saturday - 9:00 AM to 6:00 PM
WhatsApp Monday to Sunday - 24 hours
Hotline: +852 6828 1809
Instant Support: +852 9061 3106

DSE ICT | Python file handling and exception handling | with open, CSV read and write, three exceptions, four common errors

DSE ICT | Python file handling and exception handling | with open, CSV read and write, three exceptions, four common errors

  • 2026-11-06

Students open a file, forget to close it, and then let the whole program die when the file is missing, or swallow every error with a bare except and lose the traceback. Files and exceptions are one habit seen from two sides: when the resource opens and closes, and which errors to catch.

Objectives — Students can: (1) read and write text files with with open(…, encoding=”utf-8″) and explain why close is not needed by hand; (2) read 240 rows with csv.reader, skip the 12 invalid rows (5.0%) and write only the 228 valid rows to a new file; (3) write one precise except for FileNotFoundError, ValueError and ZeroDivisionError, using else and finally to separate success from cleanup.

01 Prerequisites (3-minute check)

If any of these fails, fix it before the lesson starts.

Skill Quick check Pass mark
File paths How do you refer to data.csv in the same folder? Just “data.csv”, relative to where the program runs
String handling How do you split the line “12,apple,3.5”? split(“,”) or csv.reader
Type conversion What happens with int(“abc”)? A ValueError is raised and the program stops if uncaught

02 Lesson flow (60 minutes)

Time Stage Tutor does Student does
0-6 min One deliberate crash Read a missing file and let it fail, then ask why Name the error
6-18 min with open and encoding Read, iterate, rstrip; compare with the version that forgets close Rewrite one reading block
18-30 min CSV validate and write 240 rows, 12 invalid, 228 written Write the validation condition
30-42 min Three exceptions One named except each, plus else and finally Write three excepts
42-56 min Debugging set Four broken programs, find and name each fault Fix two under time
56-60 min Exit check Collect three items, mark at once, name the fault type Work alone

03 Teaching script (read it out)

Scene 1: with open is a resource habit, not decoration

Students write f = open(…) and move on; the handle stays open, the second open on Windows fails, and the student concludes the computer is broken. Explain what with buys: the block closes the file even when an error occurs mid-way. Add encoding=”utf-8″ or Chinese data turns to mojibake or raises UnicodeDecodeError on another machine.
Put two versions side by side: three lines with with, six lines plus try/finally without. Let students count the lines; the count persuades faster than the argument.

Ask the student to convert a manual open/close block to a with block and state what is now guaranteed.

Scene 2: Read line by line, validate, then write

The usual approach reads the whole file and splits it, which fails on large files and on the first bad row. Use three stages: read with csv.reader row by row, validate (column count, score between 0 and 100), then write only the valid rows to a new file. With 240 rows and 12 invalid ones, make students compute the 95.0% pass rate before writing the if condition, so the comparison cannot be inverted.
Also insist the 12 rejected rows are logged, not silently dropped, because the log is what makes the bug findable later.

Ask the student to write the validation condition and explain why rejected rows are recorded rather than discarded.

Scene 3: A named except is the only kind worth writing

Students write except: pass, the crash disappears, and wrong data flows through unnoticed. Teach three named handlers: FileNotFoundError is a path problem (tell the user to check the name), ValueError is a data problem (log the row number and skip it), ZeroDivisionError is a logic problem (test the divisor first). Then add the rule: catch only what you can fix, and let the rest crash so the traceback points at the real line.
Close the act with else for the success path and finally for cleanup, so students see the three-part structure rather than one catch-all.

Ask the student to write a named except for each of the three programs and say why a bare except is unacceptable.

04 Question types and worked steps

Type Example Steps Answer
Read and summarise Read data.csv and average the scores with open plus csv.reader, accumulate, divide by valid count Handle blank lines and non-numeric cells
Exception identification Which exception does this program raise? Find the failing line and the conversion that fails Answer with the exception name and line number
Write mode Tell w from a w truncates, a appends Must state the consequence of overwriting
Debugging Find four faults Check resource, encoding, validation, exception in that order Each fault needs a cause and a fix
Sanity check (teach this): Sanity check: one data file only (240 rows, 12 invalid) so working memory stays on the process; every except must be named, a bare except costs the mark; validation must precede writing and rejected rows must be logged; the demo must show a second open failing after a missing close and a swallowed error from except pass, because those two consequences make the rules credible.

05 Independent practice (3 questions)

Question Answer What to watch
Convert to with Rewrite a manual open/close block Check whether encoding was added
Validate and write Keep 228 of 240 rows in a new file Check the pass rate and the rejection log
Three excepts Write a named handler for each program Check for remaining bare excepts

06 Common mistakes and what to say

Mistake Student writes Say this
Forgetting to close f = open(…) with no close The second open fails because the first still holds the file. Use with and it closes itself.
Bare except except: pass as a catch-all You caught the error and lost the reason; next time the data is wrong nobody notices. Name the exception.
Using w to append opening with “w” to add one row w wipes the file, so all 228 rows are gone. Appending needs “a”.
No encoding open(“data.csv”) gives mojibake Add encoding=”utf-8″, otherwise the file only reads on your own machine.

07 Homework (paper, section and question numbers)

08 Exit check (last 5 minutes)

Question Answer Decision
with open Closes by itself, needs encoding Cannot say why encoding matters means replay act two
Validate then write Check first, log the rejects Read then write directly means replay act two
Three exceptions FileNotFound, Value, ZeroDivision A bare except means replay act three

09 Tutor FAQ

Is the csv module required?

No, split(“,”) works until a quoted comma appears; csv is safer.

Do students need pandas?

Not for DSE, and the built-in csv is easier to write on paper.

How many exceptions to memorise?

Three: missing file, bad number, divide by zero. The rest can be looked up.

Find a tutor — freeTutor Registration →

A TutorZone lesson-prep guide. Written by the TutorZone team; questions and lesson flow are original and are not taken from any school or publisher material.

Join as a tutor or coach — academic, music, sports, arts, STEM. Free to register. See how it works →