/en-tutor-prep-ib-cs-file-processing-sequential-files-modes/
/en-tutor-prep-ib-cs-file-processing-sequential-files-modes/
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

IB Computer Science: File Processing — Tutor Lesson Plan (open modes, line-by-line I/O, closing; 300 lines at 42 bytes, a forgotten close leaves nothing)

IB Computer Science: File Processing — Tutor Lesson Plan (open modes, line-by-line I/O, closing; 300 lines at 42 bytes, a forgotten close leaves nothing)

  • 2026-11-28

Students can write open() and read(), but ask what happens when a file with data is opened in write mode and they cannot say. Files test three things: the mode sets where writing starts, line reading sets the memory, and closing decides whether the data ever reaches the disk.

Objectives — the student can (1) explain the three open modes: opening a 12,600-byte file in write mode truncates it to 0 bytes before anything is written and leaves 42 after one line, losing 12,558 bytes, while append keeps the content and grows to 12,810 after 5 more lines; (2) read 300 lines with readline and explain why readlines needs 300 times the memory; (3) write a line loop that skips bad records: 12 of 300 lines lack a comma (4.0%), so 288 valid lines remain (96.0%); (4) compute a total of 13,500 minutes, a mean of 46.9 per session, 90 sessions above 60 minutes (31.3%) and 240 to keep at 30 minutes or more (83.3%); (5) explain what a missing close costs and use a with block so the file closes even when an exception fires; (6) match the Java and Python calls: Scanner for readline, FileWriter for write, BufferedReader for the line loop.

01 Prerequisites (3-minute check)

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

Skill Quick check Pass mark
Splitting strings split “2026-11-03,P0042,45” on the comma, how many parts? 3 parts
Loop counts a file has 300 lines, how many times does for line in f run? 300, one per line
Type conversion text read from a file is a string, what is needed before adding minutes? int() to make it an integer

02 Lesson flow (60 minutes)

Time Stage Tutor does Student does
0-7 min Opening check what does write mode do to an old file? write an answer first
7-22 min The three open modes one 12,600-byte file opened three ways write three results
22-38 min Reading line by line 300 lines, 12 bad, mean 46.9 write the read loop
38-50 min Writing and appending append 5 lines to 12,810 write and append
50-57 min Closing, with and exceptions a missing close, 1,025 open files rewrite with
57-60 min Exit check three questions marked on the spot work alone

03 Teaching script (read it out)

Scene 1: The three open modes: write empties the file on sight

Open with a real case: a club sign-in file holds 300 lines at 42 bytes each, 12,600 bytes in all. A student decides to update it, opens it in write mode and every old record disappears: only the new line of 42 bytes remains and 12,558 bytes are gone for good.
Put the three modes on the board: read opens for reading only and fails if the file is missing; write truncates to 0 bytes on open and starts from the beginning; append moves the write position to the end and leaves the content alone. Ask for the sentence write is not an update, it is a rewrite, and ask what an update of one line really costs: read everything, change one record, rewrite the whole file, or use a mode that reads and writes without truncating.
Compare with numbers: the same file after 5 appended lines is 12,600 plus 5 times 42, which is 12,810 bytes; writing a single line in write mode leaves 42 bytes. The gap of 12,558 bytes is exactly 300 lines minus one. Make the class do the multiplication; that is the skeleton of the Paper 2 question on the effect of opening a file in write mode, because the mode decides the write position and the truncation, not whether the code is correct.
Close with a common confusion: append creates a missing file without error, while read raises an exception at once and needs handling.

Student task: open the same 300-line file in each mode once and record the byte count after opening and whether the old data survived.

Scene 2: Reading line by line: memory and bad records

Compare the three readers. read pulls all 12,600 bytes into memory at once; readlines builds a list of 300 strings, each with 42 bytes of content plus list overhead; readline and a for loop hold one line at a time, so memory is constant. On the same 300 lines the first two need 300 times the memory. Ask when reading it all is right: sorting by the second field needs every record in memory first.
Then write parsing as three moves: split on the comma, check that the part count is 3, convert the third part to an integer. Of 300 lines, 12 have no comma, so they split into two parts and taking the third raises IndexError, stopping the whole run on the first bad line. Catch it or test the count first, skip the record and count it: 12 bad lines is 4.0%, leaving 288 valid lines at 96.0%. Ask for the rule: skip the bad record, never let it kill the batch.
Now three statistics: 13,500 minutes across 288 valid lines gives a mean of 46.9; 90 sessions above 60 minutes is 31.3% of valid lines; 240 sessions of 30 minutes or more is 83.3%. Point at the denominator: using 300 gives 30.0%, which is wrong because a bad line has no minutes at all.
Say one line on speed: at 0.05 ms a line, 300 lines take 15.0 ms, so line reading is not slow at this size; the reason to choose it is memory, not speed.
Mention the newline: every line ends with one, so writing it back without care adds a blank line, and a line read in carries the newline, so strip before comparing.

Student task: write the read loop, skip bad records while counting them, then print the count, the mean and the sessions above 60 minutes; all three must match a hand count.

Scene 3: Closing, with and exceptions: the price of a buffer

Start with what close really does: a write goes to a buffer, not to disk, and only close or a full buffer pushes it out. So a forgotten close often survives a clean exit, but if the program raises or is killed, the buffer is lost and the file on disk can be 0 bytes. Ask for the sentence written is not the same as saved.
The second cost is the file handle: every open file holds one, the limit is about 1,024, so a loop that opens without closing fails at open number 1,025 with too many open files. The exam point is that close pairs with open, not the number.
Show the with block: with open(name) as f opens on entry and always closes on exit, including when the body raises. Ask what with buys over a manual close: nothing to remember, closing on error, one line less. If a manual close is required, wrap it in try and put close in finally.
Finish with the three sources of exceptions: a missing file, no permission, and a format error. The first two fire at open and are caught on that line; the third appears only after reading and is caught on the parse line. Have the class write the whole skeleton for the sign-in file: with, for, try, bad-line count. Those four parts are already the full-mark structure for Paper 2.

Student task: rewrite the previous read loop with a with block and add handling that prints a message instead of crashing when the file is missing.

04 Question types and worked steps

Type Example Steps Answer
Choose the open mode new records for a 12,600-byte file three steps: ask whether old data must survive, append keeps it, write replaces it, then state the byte count append gives 12,810; write gives 42
Read lines and total them 300 lines with 12 bad four steps: open with with, strip each line, split and test the part count, then add and count, skipping bad records 288 valid lines, 13,500 minutes, mean 46.9
Write with the newline write 240 records to a new file three steps: build one string per record, append the newline, write and close 240 lines; without the newline all 240 collapse into one
Close and use with the read may raise halfway two steps: put open inside with, indent all reads and writes inside the block closes on error; a manual close needs try and finally
Java against Python the same read written in both languages three pairs: Scanner against readline, FileWriter against write, BufferedReader against the line loop same concepts, different class names and exception syntax
Sanity check (teach this): Five checks: (1) byte counts stay proportional: 300 lines at 42 is exactly 12,600, and 5 appended lines add 210, so doubling is a missed multiplication; (2) percentages use the valid lines as denominator: 90 over 288 is 31.3%, while 90 over 300 gives 30.0% and is wrong; (3) a mean must sit between the lowest and highest value: 13,500 over 288 is 46.9, and 300 or 5 means the division is upside down; (4) bad plus valid equals the total: 12 plus 288 is 300; (5) write mode never updates in place: the size after write cannot exceed the original 12,600 unless more is written. The commonest misjudgement is treating a run that finished without error as data that was saved: without close, a killed program can leave 0 bytes and nothing in the code shows it.

05 Independent practice (3 questions)

Question Answer What to watch
A sign-in file has 300 lines at 42 bytes. (a) How many bytes? (b) After 5 appended lines? (c) After writing one line in write mode? (a) 12,600; (b) 12,810; (c) 42 append adds, write truncates; keep the unit in every answer
12 of 300 lines lack a comma and the valid lines total 13,500 minutes. (a) What share is valid? (b) What is the mean? (c) How should a bad line be handled? (a) 288 lines, 96.0%; (b) 46.9 minutes; (c) test the part count or catch the exception, skip it and count it denominator is the valid lines, not the total
240 records of 30 minutes or more must be kept. (a) What share of valid lines is that? (b) What happens if the newline is omitted when writing? (a) 83.3%; (b) all 240 records collapse into one line and read back as 1 line the newline is the record boundary, not decoration

06 Common mistakes and what to say

Mistake Student writes Say this
Using write mode to update a file open(“visits.txt”, “w”) to change one line write truncates to 0 bytes on open, so 12,600 bytes are gone before you write anything. Either append the new record or read everything, change one item and rewrite the whole file.
Treating a written file as saved no close before the program is killed a write goes to a buffer and only close pushes it to disk. Without close a killed program can leave 0 bytes. A with block closes for you, even on error.
Letting one bad line stop the batch line five has no comma so int() raises one malformed line should not stop 300. Test the part count or catch the exception, skip the record and report it: 12 bad lines counted, the other 288 still processed.
Wrong denominator answering 30.0% for sessions above 60 minutes a bad line has no minutes, so it cannot be in the denominator. Of 288 valid lines, 90 is 31.3%, not 30.0%.

07 Homework (paper, section and question numbers)

08 Exit check (last 5 minutes)

Question Answer Decision
Modes write on a 12,600-byte file, nothing written yet 12,600 means truncation was missed
Readers memory ratio of readlines to a line loop 1x means the two are confused
Statistics 90 sessions above 60 minutes as a share 30.0% means the denominator is wrong

09 Tutor FAQ

Which file syntax does IB examine?

Paper 2 uses whichever language the school chose, and both are accepted. The concepts are identical: open, read all or line by line, write, close. Only the names differ: Java uses Scanner to read, FileWriter to write and BufferedReader for lines; Python uses open with read, readline, write and close.

Why insist on with?

It is not compulsory but it solves two problems at once: the file always closes on exit, and it closes even when the body raises. A missing manual close is a leaked handle, and 1,025 of them fail. In an exam, with guarantees closing, including on exception, is enough.

Should a bad line be skipped or fatal?

In a batch, skip it and count it, because one bad line should not waste the other few hundred; but report how many were skipped, or nobody knows the data is short. If the question demands complete data, stop and report. Give the reason for whichever you choose.

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 →