File Processing and Exception Handling
Storing, finding and changing records in serial, sequential and random files, and handling exceptions so that a program does not halt when something unexpected happens.
File processing: text files and random files
Open a file in a mode, use it, then close it; how you add records depends on the file's organisation.
A file is opened in a mode before use, and closed afterwards.
| Word | What it does |
|---|---|
| READ | mode: reads from the start |
| WRITE | mode: creates a new file, destroying anything already in it |
| APPEND | mode: adds to the end |
| READFILE | reads the next line |
| WRITEFILE | writes one line |
| EOF() | is TRUE when nothing is left to read |
| How a record is added or found | |
|---|---|
| Serial file | it is added to by appending |
| Sequential file | it stays in key order, so a new record is inserted by copying the file into a new one, as below |
| Random file | it normally holds fixed-length records. SEEK moves the file pointer to a record's address. Then GETRECORD reads that record, or PUTRECORD replaces it. |
// Old.txt holds Anu, Bat, Dorj, Tuya, // in name order DECLARE Line : STRING DECLARE NewName : STRING DECLARE Placed : BOOLEAN NewName ← "Chimeg" OPENFILE "Old.txt" FOR READ OPENFILE "New.txt" FOR WRITE Placed ← FALSE WHILE NOT EOF("Old.txt") READFILE "Old.txt", Line IF Placed = FALSE AND Line > NewName THEN WRITEFILE "New.txt", NewName Placed ← TRUE ENDIF WRITEFILE "New.txt", Line ENDWHILE IF Placed = FALSE THEN WRITEFILE "New.txt", NewName ENDIF CLOSEFILE "Old.txt" CLOSEFILE "New.txt" // New.txt now holds // Anu, Bat, Chimeg, Dorj, Tuya
A record as a line of text
To store a record in a text file, join its fields into one string; to read it, cut the string up again.
A text file of records often holds one record on each line. A text file holds only strings.
To write a record:
- Turn a number field into a string with NUM_TO_STR.
- Join the fields into one string with &, with a comma between them.
To read the record back, read its line and cut it into fields again. Here every code is 4 digits long, so:
- LEFT takes the code
- RIGHT takes the rest, after the comma
- STR_TO_NUM turns the code back into a number
Example:The code 1042 and the name Glue become the line 1042,Glue.
Watch out:Every program that uses the file must agree on this layout, or the fields come back wrong.
TYPE StockItem DECLARE Code : INTEGER DECLARE Name : STRING ENDTYPE DECLARE Item : StockItem DECLARE Copy : StockItem DECLARE OutLine : STRING DECLARE InLine : STRING Item.Code ← 1042 Item.Name ← "Glue" OutLine ← NUM_TO_STR(Item.Code) & "," & Item.Name OPENFILE "Stock.txt" FOR WRITE WRITEFILE "Stock.txt", OutLine CLOSEFILE "Stock.txt" OPENFILE "Stock.txt" FOR READ READFILE "Stock.txt", InLine CLOSEFILE "Stock.txt" Copy.Code ← STR_TO_NUM(LEFT(InLine, 4)) Copy.Name ← RIGHT(InLine, LENGTH(InLine) - 5) OUTPUT Copy.Name, " has code ", Copy.Code
Searching a serial file
A serial file keeps records in arrival order, so a search must read them one by one from the start.
A serial file holds its records in the order they arrived. Each new record is added at the end, with OPENFILE … FOR APPEND.
A record's place has nothing to do with its key. So a search must:
- start at the first record
- read each record in turn
- stop when it finds the key, or when EOF is TRUE
If the key is not in the file, every record is read.
Example:Try the presets. 1042 is found after 4 reads. But 1028 is not in the file, so all 6 records are read.
Searching a sequential file
A sequential file keeps its keys in order, so a search can stop early once it passes the key.
A sequential file holds its records in order of a key field.
A search still starts at the first record, but it can stop early. The keys only get bigger. So once it reads a key greater than the one it wants, the wanted record cannot be further on.
The loop stops at the first key that is equal or greater. Then it checks which it was.
| Search for 1028 (missing) | Records read |
|---|---|
| serial file | all 6 |
| sequential file | 3: it stops at 1030 |
Watch out:A key greater than the last one still means reading to the end.
Changing a sequential file: write a new copy
You cannot change a record in the middle of a text file, so you write a new copy of the file.
A text file is read and written one line after another. So a record cannot be taken out of the middle, or changed, where it is. Instead, the program writes a new copy of the file.
| To... | Do this |
|---|---|
| delete a record | copy every line except that one |
| change a record | write its new version where the old one was, and copy the rest |
| insert a record | the same way, as in the code at the top of this page |
The lines are copied in their order, so the new file is still in key order.
Example:Here, deleting 1030 leaves 5 records in NewStock.txt.
Random files: straight to one record
In a random file the file pointer jumps straight to one record, so you can change it where it is.
A random file holds records, normally of a fixed length. Its file pointer can be moved straight to any one record, without reading the others.
| Command | What it does |
|---|---|
| SEEK | moves the pointer to an address. That is the record's position, counted from the start of the file. Or it is an address worked out from its key by a hashing algorithm. |
| GETRECORD | reads the whole record at the pointer into a variable of the record's type |
| PUTRECORD | writes a record there, replacing what was in that place |
So one record can be changed where it is:
- Read it.
- Change a field.
- Write it back.
TYPE StockItem DECLARE Code : INTEGER DECLARE Name : STRING ENDTYPE DECLARE Item : StockItem DECLARE Address : INTEGER Address ← 1042 MOD 7 // hash the key: 6 OPENFILE "Stock.dat" FOR RANDOM SEEK "Stock.dat", Address GETRECORD "Stock.dat", Item Item.Name ← "Glue stick" PUTRECORD "Stock.dat", Item CLOSEFILE "Stock.dat"
Exceptions
An exception is an unexpected event that stops a program; exception handling catches it so the program does not crash.
An exception is an unexpected event while a program runs. It stops the program working normally. For example:
- dividing by zero
- a missing file
- reading past the end of a file
- text typed where a number was expected
If nothing handles it, the program halts.
How exception handling works:
- Code that might fail goes in a watched block.
- If an exception is raised, control jumps to a handler for that kind of exception.
- The handler can recover, or give a clear message instead of crashing.
Use it wherever a program depends on things it cannot control: user input, files and network connections.
Watch out:Cambridge pseudocode has no exception syntax, so this example is Python.
friends_text = input("How many friends share 24 sweets? ")
try:
friends = int(friends_text)
each = 24 // friends
print("Each friend gets", each)
except ValueError:
print("Please type a whole number")
except ZeroDivisionError:
print("You cannot share between 0 friends")Exception handling when a file is read
Put all the file work inside try, so a missing file gives a clear message instead of halting the program.
Exam:Paper 4 mark schemes give a mark for exception handling around file access.
Put all of the file work inside try:
- opening the file
- the loop that reads and splits each line
- closing the file, after the loop but still inside the
try
If there is no file with that name, Python raises an exception. Then:
- the
exceptblock outputs a clear message - the program carries on instead of halting
Example:Here Stok.txt is a mistyped name. open() raises FileNotFoundError, and the last line still reports how many records were read.
FileName = input("File name? ")
Stock = []
try:
TheFile = open(FileName, "r")
for Line in TheFile:
Parts = Line.strip().split(",")
Stock.append(Parts)
TheFile.close()
except FileNotFoundError:
print("There is no file called", FileName)
print(len(Stock), "records read")KEY TERMS
CHECK YOURSELF
1.A text file holds 4 lines. It is opened FOR WRITE, one line is written, and it is closed. How many lines does it hold now?
2.Why should a program that reads a number typed by the user use exception handling?
3.A sequential file holds its records in key order. How does a program add a record and keep that order?
4.A serial file holds 6 records. A search looks for a key that is not in the file. How many records does it read?
5.A sequential file holds the keys 1011, 1025, 1030 and 1037, in that order. A search for 1028 stops after reading 1030. Why can it stop there?
6.Which statement reads the record at a random file's file pointer into the record variable Item?
7.A random file stores each record at its key MOD 7, and no two keys share an address. How does a program read the record with key 1042?
8.A Paper 4 program reads a text file and uses exception handling. Where should the lines that open and close the file go?