Records in text files
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.
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.
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
rstrip("\n")removes the line ending. - 2
split("|")cuts at each pipe and keeps the fields in order. - 3
intconverts the text "31" to the INTEGER 31. Status stays a STRING.
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(22, 12, 'available')
- 2Status: it is already a STRING
- 3"69": + joins two strings; after
intthey add to 15
Reading and closing text files
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.
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])
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.
- 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 stocktest 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.
| Operation | Python meaning | Pseudocode counterpart |
|---|---|---|
| Open | open(path, "r") preserves existing contents. | OPENFILE … FOR READ |
| Read | The for loop supplies the next line. | READFILE assigns the next line to a STRING. |
| Finish | Leaving 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.
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?
- 16, once per line
- 2an empty list
[] - 3EOF
Writing and appending records
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.
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.
- 1Opening with "w" removes the old obsolete line; the loop writes five lanterns.
- 2Opening with "a" adds ID 19 as the sixth record.
- 3Reloading 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.
| Mode | Existing file | Missing file |
|---|---|---|
| "r" / READ | Read; do not replace it. | Opening fails. |
| "w" / WRITE | Discard old contents, then write. | Create it. |
| "a" / APPEND | Write 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.
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?
- 11
- 23
- 3the text becomes
19|9|on-loan8|6|available: one line with 5 fields, and status and ID join ason-loan8
Sequential file processing
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.
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))
[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: 8|6|available; 14|9|on-loan; 19|9|on-loan; 22|12|available; 27|12|repair; 31|6|available.
- 1
updated.appendis outside the if, so all six records are copied in order. Only ID 8 changes. - 2The available list is a separate selection. Saving it as stock would lose the on-loan and repair records.
- 3A 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.
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[8, 31]
- 21: only the hired lantern is written
- 3the original file stays intact if the save fails
Reading random files
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.
Positions 0–5 hold IDs 19, 31, 14, 27, 8, 22: position 4 is available and position 3 is repair.
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)
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.
- 1Find the ID’s position first, with the hash and collision rule or an index.
- 2ID 8 hashes to 2 but is stored at 4 after probing. SEEK to 8 would ask for a different position.
- 3CLOSEFILE runs before RETURN on both branches. Returning from inside the IF would leave the file open.
- 4A position counts records here; a byte-based file would also need the fixed record length.
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?
- 1Ready for hire (ID 31 is available)
- 2Not available (ID 14 is on-loan)
- 3SEEK takes a record position; lantern 8 is stored at position 4
Writing random-file records
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.
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"
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.
- 1SEEK 4 and GETRECORD copy slot 4 into Item.
- 2Change only
Item.Status; ID and wattage stay as read. - 3SEEK 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.
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?
- 1the read can move the file pointer on; SEEK puts it back on slot 4 so the right record is replaced
- 2ID 14
- 3only Status: available → on-loan
When to use an exception handler
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.
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.
| Situation | Decision | Reason |
|---|---|---|
| ID 27 is in repair | Use IF to refuse the hire. | The file was read successfully; repair is an expected state. |
| Lanterns.txt is missing | Handle FileNotFoundError. | Opening cannot supply the requested data. |
| A wattage field contains six | Handle ValueError from int. | The text cannot be converted to the required integer. |
| The OS refuses file access | Handle 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.
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?
- 1IF: the data was read correctly; repair is a normal state
- 2None, after a message
- 3an empty list
[]
Implementing exception handlers
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.
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.
- 1
int("six")fails in parse_line and raises a ValueError. - 2The rest of load_records is skipped, and its with block closes the file.
- 3The first matching handler in safe_load runs and prints the message.
- 4safe_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 file | Actual output | Returned result |
|---|---|---|
| Six valid lantern lines | Loaded 6 | List of six complete records. |
| No Lanterns.txt | File missing; no data loaded | None; the caller skips processing. |
| Valid first line, then bad wattage | Read failed; no data loaded | None; the partial list is discarded. |
| Empty file | Loaded 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.
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?
- 1File missing; no data loaded
- 2FileNotFoundError is a kind of OSError, and the first matching handler runs; the missing-file message would never appear
- 3only when the try finishes without an exception
A complete file-processing task
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.
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)
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.
1 What does hire_file(27) print?
2 What does hire_file(20) print?
3 Which file does the program never change?
- 1Not available (lantern 27 is in repair)
- 2ID not found
- 3Stock.txt