Subtopic Notes
20.2 File Processing and Exception Handling
20. Further Programming
20.2 File Processing and exception handling
Handling text files
- Text files consist of lines of text that are read or written consecutively as strings
- The purpose of storing data in a file is to be used again by a program
- Data in files are stored permanently, meaning they can be used later
- It is good practice to explicitly open a file, stating the mode of operation, before reading from or writing to it.
- File can be opened in three modes:
- READ: for data to be read from the file
- WRITE: for data to be written to the file. A new file will be created and any existing data in the file will be lost
- APPEND: for data to be added to the file, after any existing data
- A file should be opened in only one mode at a time
| Python |
|---|
# Opening a file - open(filename, mode) # Modes: r = read, w = write f = open("test_file.txt", "r") print(f.read()) # Reads the full file at once print(f.readline()) # Reads one line from the file print(f.readline()) # Reads the next line from the file for x in f: #Loops through the file print(x) f.close() #Closes the file f = open("test_file2.txt", "w") f.write("Test sentence") #Writes a line in the file f.close() |
| Pseudocode |
| Opening a file OPENFILE <File identifier> FOR <File mode> The file identifier will be the name of the file with a data type of string. Data is read from the file (after opening in READ mode) using the following: READFILE <file Identifier>, <variable> When the command is executed, the data item is read and assigned to the variable (the data type is string) To test whether there are any more lines to be read from the file EOF(<file identifier>) This function returns TRUE if there are no more lines to read (or if an empty file has been opened in READ mode) and FALSE otherwise Data is written into the file after opening using the following command: WRITEFILE <file identifier>, <variable> When the command is executed, the data is written into the file. Files should be closed when they are no longer needed. CLOSEFILE <file identifier> //Closes the file This example uses the operations together, to copy all the lines from FileA.txt to FileB.txt**, replacing any blank lines by a line of dashes.** DECLARE LineOfText : STRING OPENFILE "FileA.txt" FOR READ OPENFILE "FileB.txt" FOR WRITE WHILE NOT EOF("FileA.txt") READFILE "FileA.txt", LineOfText IF LineOfText = "" THEN WRITEFILE "FileB.txt", " ----------------------------" ELSE WRITEFILE "FileB.txt", LineOfText ENDIF ENDWHILE CLOSEFILE "FileA.txt" CLOSEFILE "FileB.txt" |
Handling random files
- Random files contain a collection of data, normally as records of fixed length.
- They can be thought of as having a file pointer which can be moved to any location or address in the file.
- The record at that location can then be read or written.
| Pseudocode |
|---|
| Random files are opened using the RANDOM file mode as follows: OPENFILE <file identifier> FOR RANDOM As with text files, the file identifier will normally be the name of the file. The SEEK command moves the file pointer to a given location: SEEK <file identifier>, <address> The address should be an expression that evaluates to an integer which indicates the location of a record to be read or written. This is usually the number of records from the beginning of the file. It is good practice to explain how the addresses are computed. The command GETRECORD should be used to read the record at the file pointer: GETRECORD <file identifier>, <variable> When this command is executed, the record that is read is assigned to the variable which must be of the appropriate data type for that record (usually a user-defined type). The command PUTRECORD is used to write a record into the file at the file pointer: PUTRECORD <file identifier>, <variable> When this command is executed, the data in the variable is inserted into the record at the file pointer. Any data that was previously at this location will be replaced. Example – handling random files The records from positions 10 to 20 of a file StudentFile.Dat are moved to the next position and a new record is inserted into position 10. The example uses the user-defined type Student defined in page 68. DECLARE Pupil : Student DECLARE NewPupil : Student DECLARE Position : INTEGER NewPupil.LastName ← "Johnson" NewPupil.Firstname ← "Leroy" NewPupil.DateOfBirth ← 02/01/2005 NewPupil.YearGroup ← 6 NewPupil.FormGroup ← ꞌAꞌ OPENFILE "StudentFile.Dat" FOR RANDOM FOR Position ← 20 TO 10 STEP -1 SEEK "StudentFile.Dat", Position GETRECORD "StudentFile.Dat", Pupil SEEK "StudentFile.Dat", Position + 1 PUTRECORD "StudentFile.Dat", Pupil NEXT Position SEEK "StudentFile.Dat", 10 PUTRECORD "StudentFile.Dat", NewPupil CLOSEFILE "StudentFile.dat" |
| Python |
Serial Access (Writing Records One After Another) Serial access processes data in the order it is received. //Example: Appending log entries to a file from datetime import datetime message = "System started" timestamp = datetime.now().strftime("%H:%M") log = f"{timestamp} - {message}\n" with open("logfile.txt", "a") as file: file.write(log) Sequential Access (Reading All Records in Order)Sequential access reads records from start to end. //Example: Reading student records line by line with open("students.txt", "r") as file: for line in file: name, grade = line.strip().split(",") print("Name:", name, "Grade:", grade) Random Access (Accessing a Specific Record) Random access allows direct access to a specific record. //Example: Updating a student’s grade using record number record_number = 4 # 5th record (0-indexed) with open("students.txt", "r") as file: records = file.readlines() name, grade = records[record_number].strip().split(",") records[record_number] = f"{name},90\n" with open("students.txt", "w") as file: file.writelines(records) |
Exception Handling
- Refers to the way a program detects and responds to such errors, allowing it to recover or terminate gracefully instead of crashing.
- Exception: Unexpected event that interrupts the normal flow of a program
- Uses
- Prevents programs from crashing suddenly
- Provides clear and user-friendly error messages
- Makes software more stable and reliable
- Manages common errors
- Causes of exceptions
- Programming errors - such as using uninitialized variables or making logical mistakes.
- Hardware or device failures - like a disk read error, printer disconnection, or other hardware malfunctions.
- Division by zero
- File errors - when a file is missing, unreadable, or cannot be accessed.
- Invalid input
Exception Handling Using try and except (Python)
Example: File Not Found
try: file = open("data.txt", "r") print(file.read()) file.close() except FileNotFoundError: print("File does not exist") |
|---|
Multiple Exception
try: num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) result = num1 / num2 print("Result:", result) except ZeroDivisionError: print("Cannot divide by zero") except ValueError: print("Invalid input") finally: print("Program ended") |
|---|
File Handling with Exception Handling
try: file = open("marks.txt", "r") for line in file: print(line.strip()) except FileNotFoundError: print("Marks file not found") finally: file.close() |
|---|
