University of Melbourne · FACULTY OF COMPUTER SCIENCE

COMP90059 Chap.9 Files and Recursive Functions

- one subject, every graph, every model, every mark
12 Chapters3-page Bible
Our own words - no uploaded lecturer files
Updated for this semester
Chapter 9 of 9 · COMP90059

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.

In this chapter

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

Q [5 marks]. A function returns zero at n equal to zero and otherwise returns n plus the function called on n minus one. Trace the call on 4. The marks shown map the trace for practice and are not official assessment weighting.
A file workflow has a resource boundary around a separate parsing pipeline.A file workflow has a resource boundary around a separate parsing pipeline.openchoose modeprocessread linesparse + validatecloserelease safely
A file workflow has a resource boundary around a separate parsing pipeline.
  • 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.
The call returns 10. Each positive frame waits with one pending addition and the zero base starts the unwinding.
Sia tip — Trace recursion in two columns: arguments on descent and returned values on ascent.
Glossary

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.
FAQ

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.

Study strategy

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.

A+Everything unlocked
Unlocks this Bible + all 177 of your University of Melbourne subjects - and 1,000+ Bibles across every Australian university.
Sia - your COMP90059 tutor, unlimited, worked the way the exam marks it
The full 3-page Bible + practice bank with worked solutions
Chrome extension - sync your LMS so Sia knows your deadlines
Bilingual EN / Chinese on every Bible and every Sia answer
$0.99 Trial
30-day money-back · cancel in one tap · how it works