Skip to content

9618 · Unit 24 · Papers 3–4: Theory and practical programming

File processing and exception handling.

9618 · Unit 24 · File processing and exception handling
Revisionbyexamplicity

Records in text files

§20.2 · File processing and exception handling

A program’s lists vanish when it stops. A text file keeps them, but only as characters. To get a record back, cut each line at its field boundaries and convert each field to the type the program needs.

Tavren stores one lantern per line, in arrival order, with fields ID | Wattage | Status. The pipe separator never occurs inside a field. There is no header line.

Lanterns.txt · complete contents
31|6|available
14|9|on-loan
27|12|repair
8|6|available
22|12|available
19|9|on-loan

Cut one line into three typed fields

Until it is cut up, a line is one string. Be able to name each step that turns it into a record.

One line of Lanterns.txt\n: removed by rstrip31|6|available\n"31"int31INTEGER"6"int6INTEGER"available"kept'available'STRING(31, 6, 'available')
Python
def parse_line(line):
parts = line.rstrip("\n").split("|")
ID, wattage, status = parts
return (int(ID), int(wattage), status)
item = parse_line("31|6|available\n")
print(item)
  1. 1
    rstrip("\n") removes the line ending.
  2. 2
    split("|") cuts at each pipe and keeps the fields in order.
  3. 3
    int converts the text "31" to the INTEGER 31. Status stays a STRING.
If a task uses commas or spaces between fields, split at that. If each field is on its own line, read them in order and build the record once every field is read.
Your turn

1 What does parse_line("22|12|available\n") return?

2 Which of the three fields is never converted?

3 Two wattages are read as the text "6" and "9" and joined with +. What do you get, and why convert first?

  1. 1
    (22, 12, 'available')
  2. 2
    Status: it is already a STRING
  3. 3
    "69": + joins two strings; after int they add to 15
Tick what you can do now
Practise with s26/42 Q2(b)(i); s26/43 Q2(b)
1 / 9
9618 · Unit 24 · File processing and exception handling
Revisionbyexamplicity

Reading and closing text files

§20.2 · File processing and exception handling

Stored records are no use until the program reads them into memory. Open the file in read mode, read each line, build its record and keep the collection. Close the file when the operation ends.

Lanterns.txt holds six ID|Wattage|Status lines and no header. parse_line, from the last page, turns one line into a record.

Parse each ID|Wattage|Status line
def load_records(path):
records = []
with open(path, "r", encoding="utf-8") as source:
for line in source:
records.append(parse_line(line))
return records
stock = load_records("Lanterns.txt")
print(len(stock))
if stock:
print(stock[0])
print(stock[-1])
Output
6
(31, 6, 'available')
(19, 9, 'on-loan')

The loop stops at end of file

The program never needs to know the file’s length. Each pass reads the next line and appends one record; be able to say when the loop stops.

Lanterns.txtrecords after each pass31|6|available1(31, 6, 'available')14|9|on-loan2(14, 9, 'on-loan')27|12|repair3(27, 12, 'repair')8|6|available4(8, 6, 'available')22|12|available5(22, 12, 'available')19|9|on-loan6(19, 9, 'on-loan')end of fileloop stops: 6 records
  • The loop does not count to six: it stops when no line is left (end of file).
  • An empty file gives an empty list, so the program prints 0.
  • The if stock test skips the first and last records when the list is empty.

The same steps in pseudocode

Pseudocode names each step that Python does quietly for you.

OperationPython meaningPseudocode counterpart
Openopen(path, "r") preserves existing contents.OPENFILE … FOR READ
ReadThe for loop supplies the next line.READFILE assigns the next line to a STRING.
FinishLeaving with closes the file, even if the body raises an exception.Test EOF before READFILE; CLOSEFILE when finished.

return records comes after the with block, so the file is already closed. The caller must store the returned list, or later code cannot use it.

Your turn

1 How many times does the loop body run for Lanterns.txt?

2 What does load_records return for an empty file?

3 Which pseudocode function tells you there are no more lines to read?

  1. 1
    6, once per line
  2. 2
    an empty list []
  3. 3
    EOF
Tick what you can do now
Practise with s26/43 Q2(b), Q2(d)(i); s26/42 Q2(b)(i)
2 / 9
9618 · Unit 24 · File processing and exception handling
Revisionbyexamplicity

Writing and appending records

§20.2 · File processing and exception handling

Saving can add to a file or wipe it, and a wiped file cannot be got back. Write mode creates a file or replaces its contents. Append mode keeps the existing contents and adds new data at the end. So choose the mode before opening.

Five records go in with write mode and the sixth with append. Reading the file back checks that nothing was lost.

Write five arrival records, then append the sixth
def save_records(path, records):
with open(path, "w", encoding="utf-8") as target:
for ID, wattage, status in records:
line = f"{ID}|{wattage}|{status}\n"
target.write(line)
stock = load_records("Lanterns.txt")
save_records("ArrivalLog.txt", stock[:5])
with open("ArrivalLog.txt", "a") as target:
target.write("19|9|on-loan\n")
print(load_records("ArrivalLog.txt") == stock)

What the file holds after each step

The moment of opening decides whether old data survives. Be able to say what the file holds after each open.

before1 lineobsoleteafter "w"5 lines31|6|available14|9|on-loan27|12|repair8|6|available22|12|availableafter "a"6 lines31|6|available14|9|on-loan27|12|repair8|6|available22|12|available19|9|on-loan
  1. 1
    Opening with "w" removes the old obsolete line; the loop writes five lanterns.
  2. 2
    Opening with "a" adds ID 19 as the sixth record.
  3. 3
    Reloading compares every field of every record with stock and prints True.

Read, write or append: which mode?

Each mode treats an existing file differently. Find the mode, then read what it does to a file that exists and to one that does not.

ModeExisting fileMissing file
"r" / READRead; do not replace it.Opening fails.
"w" / WRITEDiscard old contents, then write.Create it.
"a" / APPENDWrite after the existing data.Create it.

Write a newline after each record, or the last field of one lantern joins the next lantern’s ID. Close the file so pending output is completed and the resource is released.

Your turn

1 A file holds two lines. It is opened with "w" and one record is written. How many lines does it hold now?

2 The same two-line file is opened with "a" and one record is written. How many lines now?

3 The newline is left out after 19|9|on-loan, and 8|6|available is written next. What goes wrong?

  1. 1
    1
  2. 2
    3
  3. 3
    the text becomes 19|9|on-loan8|6|available: one line with 5 fields, and status and ID join as on-loan8
Tick what you can do now
Practise with w24/21 Q8(b–c) (older Paper 2: write/append transfer practice)
3 / 9
9618 · Unit 24 · File processing and exception handling
Revisionbyexamplicity

Sequential file processing

§20.2 · File processing and exception handling

You cannot change one line in the middle of a text file; you write the file out again. A sequentially organised file is stored in key order. A read–modify–write pass updates one record and copies every other record unchanged.

Stock.txt holds the same six lanterns, this time in ID order. Task: hire ID 8 only if it is available, write the whole revised collection, then list the IDs still available.

Use load_records and save_records already defined
stock = load_records("Stock.txt")
updated = []
for ID, wattage, status in stock:
if ID == 8 and status == "available":
status = "on-loan"
updated.append((ID, wattage, status))
save_records("Updated.txt", updated)
available = []
for ID, wattage, status in updated:
if status == "available":
available.append(ID)
print(available)
print(len(updated))
Output
[22, 31]
6

Copied, changed or selected?

The program does three different things to these records. Be able to show which are copied, which one changes, and which are selected.

Stock.txt (kept)Updated.txt8|6|availablechange8|6|on-loan14|9|on-loancopy14|9|on-loan19|9|on-loancopy19|9|on-loan22|12|availablecopy22|12|available✓27|12|repaircopy27|12|repair31|6|availablecopy31|6|available✓available = [22, 31]

Stock.txt: 8|6|available; 14|9|on-loan; 19|9|on-loan; 22|12|available; 27|12|repair; 31|6|available.

  1. 1
    updated.append is outside the if, so all six records are copied in order. Only ID 8 changes.
  2. 2
    The available list is a separate selection. Saving it as stock would lose the on-loan and repair records.
  3. 3
    A serial arrival log is read the same way, but it stays in arrival order: reading records one after another does not make a file sequentially organised.
Your turn

1 The program hires ID 22 instead of ID 8. What does it print for available?

2 updated.append is moved inside the if. How many records does Updated.txt hold?

3 Why does the program write Updated.txt rather than overwrite Stock.txt?

  1. 1
    [8, 31]
  2. 2
    1: only the hired lantern is written
  3. 3
    the original file stays intact if the save fails
Tick what you can do now
Practise with s26/42 Q2(c)(i); s26/43 Q2(e)(i) (related filtering practice)
4 / 9
9618 · Unit 24 · File processing and exception handling
Revisionbyexamplicity

Reading random files

§20.2 · File processing and exception handling

Reading every line to find one lantern is slow in a large file. A random file jumps straight to it, because its records sit at numbered positions. SEEK moves the file pointer to a position; GETRECORD reads the record there into a variable of the right type.

Status.dat holds fixed-size status records at positions 0–5, counted from the start. Each status field reserves nine characters; shorter values are padded.

Pos.status record0on-loanlantern 191availablelantern 312on-loanlantern 143repairlantern 274availablelantern 85availablelantern 22SEEK … , 4pointer at ID 8SEEK … , 8 is wrong:8 hashes to slot 2 (ID 14)

Positions 0–5 hold IDs 19, 31, 14, 27, 8, 22: position 4 is available and position 3 is repair.

Official random-file operations · zero-based positions
FUNCTION HireState(Position : INTEGER) RETURNS STRING
DECLARE Status, Response : STRING
OPENFILE "Status.dat" FOR RANDOM
SEEK "Status.dat", Position
GETRECORD "Status.dat", Status
IF Status = "available" THEN
Response ← "Ready for hire"
ELSE
Response ← "Not available"
ENDIF
CLOSEFILE "Status.dat"
RETURN Response
ENDFUNCTION
OUTPUT HireState(4)
OUTPUT HireState(3)
Output
Ready for hire
Not available

Turn the ID into a position first

SEEK needs a position, not an ID, and the two are rarely the same. Be able to turn one into the other first.

  1. 1
    Find the ID’s position first, with the hash and collision rule or an index.
  2. 2
    ID 8 hashes to 2 but is stored at 4 after probing. SEEK to 8 would ask for a different position.
  3. 3
    CLOSEFILE runs before RETURN on both branches. Returning from inside the IF would leave the file open.
  4. 4
    A position counts records here; a byte-based file would also need the fixed record length.
Your turn

1 What does HireState(1) output?

2 What does HireState(2) output?

3 Why must the caller pass 4, not 8, to find lantern 8?

  1. 1
    Ready for hire (ID 31 is available)
  2. 2
    Not available (ID 14 is on-loan)
  3. 3
    SEEK takes a record position; lantern 8 is stored at position 4
Tick what you can do now
Practise with s26/32 Q10(b)
5 / 9
9618 · Unit 24 · File processing and exception handling
Revisionbyexamplicity

Writing random-file records

§20.2 · File processing and exception handling

To change one field in a random file, you put the whole record back in its slot. PUTRECORD writes a whole record at the file pointer, replacing the record already there. Read it, change a field, then seek back before writing.

Lanterns.dat holds six fixed-length LanternRecord slots, in the same hash-table order as Status.dat. ID 8 is available at position 4. Its ID and wattage must survive the status update.

Pseudocode
TYPE LanternRecord
DECLARE ID, Wattage : INTEGER
DECLARE Status : STRING
ENDTYPE
DECLARE Item : LanternRecord
OPENFILE "Lanterns.dat" FOR RANDOM
SEEK "Lanterns.dat", 4
GETRECORD "Lanterns.dat", Item
OUTPUT Item.ID, " ", Item.Status
Item.Status ← "on-loan"
SEEK "Lanterns.dat", 4
PUTRECORD "Lanterns.dat", Item
SEEK "Lanterns.dat", 4
GETRECORD "Lanterns.dat", Item
OUTPUT Item.ID, " ", Item.Status
CLOSEFILE "Lanterns.dat"
Output
8 available
8 on-loan

Write back to the same slot

Written to the wrong slot, the record wipes out another lantern. Follow the numbers: the record goes into Item and comes back to the same slot.

Pos.ID · Wattage · Status019 · 9 · on-loan131 · 6 · available214 · 9 · on-loan327 · 12 · repair48 · 6 · on-loan522 · 12 · availableItem : LanternRecordID8Wattage6Statusavailableon-loan123
  1. 1
    SEEK 4 and GETRECORD copy slot 4 into Item.
  2. 2
    Change only Item.Status; ID and wattage stay as read.
  3. 3
    SEEK 4 again, then PUTRECORD writes the whole record back. Writing at hash slot 2 would replace ID 14.
  • A fixed record size lets a position mark where a record starts; a variable-length text line cannot.
Your turn

1 Why does the program SEEK to 4 a second time before PUTRECORD?

2 Which lantern is lost if the record is written at slot 2?

3 Which field of slot 4 changes?

  1. 1
    the read can move the file pointer on; SEEK puts it back on slot 4 so the right record is replaced
  2. 2
    ID 14
  3. 3
    only Status: available → on-loan
Tick what you can do now
Practise with s25/32 Q13 (older paper: random update)
6 / 9
9618 · Unit 24 · File processing and exception handling
Revisionbyexamplicity

When to use an exception handler

§20.2 · File processing and exception handling

Files go missing and data arrives garbled. A program that simply crashes can take good data down with it. An exception interrupts normal execution when an operation fails at runtime. An exception handler gives a controlled response, so the program can recover or stop the operation sensibly.

Every protected load ends one of two ways. Follow each branch down to what the program may do next.

try: load complete filesuccessexceptionreturn recordsincluding [] if emptymessage + Nonediscard partial loadquery / updatestop; keep old data

IF or exception handler?

Not every problem is an exception. Be able to decide, for each situation, whether an IF or an exception handler deals with it.

SituationDecisionReason
ID 27 is in repairUse IF to refuse the hire.The file was read successfully; repair is an expected state.
Lanterns.txt is missingHandle FileNotFoundError.Opening cannot supply the requested data.
A wattage field contains sixHandle ValueError from int.The text cannot be converted to the required integer.
The OS refuses file accessHandle OSError.The file operation cannot complete.

What to protect, and what to return

A handler in the wrong place can still let half-loaded data through.

  • Protect opening, reading and conversion together.
  • Return records only after the whole load succeeds: a bad later line must not let a partial list replace valid stock.
  • An empty file succeeds with []; a failed load returns None. The caller checks which, reports a failure and stops before processing or saving.
  • Ignoring a failure silently leaves the program’s state uncertain.
Your turn

1 Lantern 27’s status is "repair". Is that an exception or a case for IF?

2 Lanterns.txt is missing. What does the protected load return?

3 Lanterns.txt exists but is empty. What does the load return?

  1. 1
    IF: the data was read correctly; repair is a normal state
  2. 2
    None, after a message
  3. 3
    an empty list []
Tick what you can do now
Practise with s26/42 Q2(b)(i); s26/43 Q2(b)
7 / 9
9618 · Unit 24 · File processing and exception handling
Revisionbyexamplicity

Implementing exception handlers

§20.2 · File processing and exception handling

A handler is worth writing only for a fault you can do something useful about. Catch the exception types the operation can meaningfully handle. After a fault, execution jumps to the matching handler; it does not go back to the failed statement.

Uses load_records and parse_line
def safe_load(path):
try:
records = load_records(path)
except FileNotFoundError:
print("File missing; no data loaded")
return None
except (OSError, ValueError):
print("Read failed; no data loaded")
return None
else:
return records
stock = safe_load("Lanterns.txt")
if stock is not None:
print("Loaded", len(stock))

Follow one exception up the calls

The fault happens deep inside parse_line, but the handler is two calls up. Line 2 of the file is 8|six|available; follow the numbers.

callerstock = safe_load(...)safe_loadtry: load_records(path)load_recordsline 2: parse_line(line)parse_lineint("six") failsValueError12handlerexcept (OSError,ValueError):prints Read failed3return None4
  1. 1
    int("six") fails in parse_line and raises a ValueError.
  2. 2
    The rest of load_records is skipped, and its with block closes the file.
  3. 3
    The first matching handler in safe_load runs and prints the message.
  4. 4
    safe_load returns None; the caller skips processing.

One test file for each path through the handler. Check each printed line against the result safe_load returns.

Test fileActual outputReturned result
Six valid lantern linesLoaded 6List of six complete records.
No Lanterns.txtFile missing; no data loadedNone; the caller skips processing.
Valid first line, then bad wattageRead failed; no data loadedNone; the partial list is discarded.
Empty fileLoaded 0[]; a successful empty collection.
  • FileNotFoundError is a kind of OSError, so its handler comes first.
  • The second handler also covers conversion failures.
  • else runs only when the try finishes normally.
Your turn

1 What does the program print if Lanterns.txt is missing?

2 Why must the FileNotFoundError handler come before the OSError handler?

3 When does the else part run?

  1. 1
    File missing; no data loaded
  2. 2
    FileNotFoundError is a kind of OSError, and the first matching handler runs; the missing-file message would never appear
  3. 3
    only when the try finishes without an exception
Tick what you can do now
Practise with s26/42 Q2(b)(i); s26/43 Q2(b)
8 / 9
9618 · Unit 24 · File processing and exception handling
Revisionbyexamplicity

A complete file-processing task

§20.2 · File processing and exception handling

A real hire uses every step at once, and any of them can fail. Join the operations in a testable order: load → find → change → save → reload. Keep the original file while writing the revised version, and report the actual result.

Use parse_line, load_records, save_records and safe_load from the earlier pages. Stock.txt: 8|6|available; 14|9|on-loan; 19|9|on-loan; 22|12|available; 27|12|repair; 31|6|available.

Five stages, and where each can stop

Black: what the stage passes on. Amber: where the task ends early.

1 · loadsafe_load: 6 records from Stock.txtNone → stop; nothing is saved2 · findID 8 found, status availablemissing or not available → print result, no save3 · changestatus available → on-loan; result Hire saved4 · save6 records written to Updated.txtOSError → Save failed; keep Stock.txt5 · reloadreloaded list == updated: True
Python
def hire_file(ID):
stock = safe_load("Stock.txt")
if stock is None:
return
updated = []
result = "ID not found"
for key, watts, status in stock:
if key == ID:
result = "Not available"
if status == "available":
status = "on-loan"
result = "Hire saved"
updated.append((key, watts, status))
if result == "Hire saved":
try:
save_records("Updated.txt", updated)
check = load_records("Updated.txt")
except OSError:
print("Save failed; keep Stock.txt")
return
print("Reload matches:", check == updated)
print(result)
hire_file(8)
Output
Reload matches: True
Hire saved
  • The reload checks every saved field and its order.
  • A repair or on-loan lantern gives Not available; a missing ID gives ID not found. Both are normal paths and leave Stock.txt intact.
  • A failed load ends the task before anything is saved.
Your turn

1 What does hire_file(27) print?

2 What does hire_file(20) print?

3 Which file does the program never change?

  1. 1
    Not available (lantern 27 is in repair)
  2. 2
    ID not found
  3. 3
    Stock.txt
Tick what you can do now
Practise with s26/43 Q2(b), Q2(d), Q2(e); s26/42 Q2(b–c) (related loading, selection and test-output practice)
9 / 9