COMP90059 Chap.9 Files and Recursive Functions
Files and Recursive Functions
Files introduce an external data boundary. Read mode observes existing content, write mode replaces content and append mode adds at the end, so the mode expresses a material effect rather than a cosmetic option. A context manager keeps the file lifetime explicit and closes the resource even when processing fails. Lines should be parsed into temporary values, validated completely and only then committed to program state.
Recursion introduces a different boundary: a base case returns without another call, and every recursive path must move toward it. Each call has its own local frame and waits for a smaller call before the result is assembled during unwinding. Code reading connects both topics by tracing contracts, state and edge cases.
What this chapter covers
- 01
Read mode observes existing file content
- 02
Write mode replaces content and requires deliberate use
- 03
Append mode adds content without discarding earlier records
- 04
Context managers close files reliably
- 05
Parsing should finish before state is updated
- 06
A recursive base case ends the call chain
- 07
A recursive argument must become smaller or simpler
- 08
Unwinding combines returned values from waiting calls
- 09
Text files expose strings even when records represent numeric values
- 10
Line processing should distinguish end-of-file from an empty field
- 11
Recursive specifications separate the smallest solved input from reduction
- 12
Resource and parsing errors belong to different diagnostic layers
Worked example · free
Trace a recursive sum
- 1Calls descend through arguments 4, 3, 2, 1 and 0.
- 1The base case at zero returns without another recursive call.
- 1The first unwinding result is 1 plus 0, which equals 1.
- 1Further unwinding produces 3, then 6, then 10.
- 1The decreasing nonnegative argument proves progress toward the base case.
Key terms
- File mode
- The access rule chosen when opening a file, such as reading, replacing or appending content.
- Context manager
- A with block that controls resource lifetime and closes the opened file when the block ends.
- Parsing boundary
- The point where external text is converted and validated before entering trusted program state.
- Base case
- A recursive input that returns directly without making another recursive call.
- Recursive case
- The branch that calls the same function on a smaller or simpler problem and combines its answer.
- Call stack
- The active function frames waiting for nested or recursive calls to return.
- Record validation
- Checking the shape and contents of one external record before it changes trusted program state or contributes to a calculation.
- Progress measure
- A well-founded quantity that becomes smaller on every recursive call and therefore supports the argument that the base case will be reached.
- Stack unwinding
- The return phase in which waiting recursive frames resume in reverse call order and combine the values produced below them.
Files and Recursive Functions FAQ
Why is write mode dangerous for an existing log?
Write mode replaces existing content. If the intention is to retain earlier records and add a new one, append mode expresses that effect, but the program should still validate the target path.
Why use a with block for files?
It bounds the file lifetime and closes the resource reliably, including when an exception interrupts processing inside the block, so cleanup is tied to a visible lexical region.
How do I know recursion will stop?
Identify a base case and a progress measure. Every recursive path must move the input toward that base while staying inside the function precondition and avoiding a cycle of equivalent inputs.
How should I trace a recursive return?
Record calls while descending to the base, then substitute returned values while unwinding. Do not mix pending operations with completed values or skip the combination performed by each waiting frame.
Where should malformed file content be handled?
Convert and validate each external record at the parsing boundary before updating totals or collections. Keep missing-file and permission failures distinct from malformed-content cases, because they describe different broken assumptions and usually require different responses.
How can I compare an iterative and recursive solution?
Identify the state each version carries, the condition that stops it and the operation that combines partial results. Trace both on the same small input, including the empty or base case. Prefer the form whose state and failure boundaries are clearest, while recognising that deep recursion also consumes call-stack space.
Exam move
Write three tiny file exercises: count valid numeric lines, append one labelled result and copy only fully validated records to a new file. Test an empty file, a blank line, a malformed value and a missing path, keeping path failures separate from content failures. For recursion, trace a countdown, a sum and one sequence problem with a clear smaller input. Write the base case, progress measure and combination rule before code.
Compare one recursive solution with an iterative version and explain which makes the state clearer. End with mixed code reading: identify inputs, outputs, mutations, branches, loop state and recursive frames before predicting the final result.
Working through Files and Recursive Functions in COMP90059? Sia is AskSia’s AI Computer Science tutor — ask any COMP90059 Files and Recursive Functions question and get a clear, step-by-step explanation grounded in how COMP90059 is taught and assessed. Read this chapter free, then take your hardest questions to Sia.