📑 Contents

Chapter 20.2: File Processing & Exception Handling

9618 Computer Science - Python Programming

📚 Learning Objectives
📖 Prior Knowledge Required
🌟 Did You Know?

File processing and exception handling are essential skills for building robust applications. Without proper file handling, data would be lost when a program ends. Without exception handling, a single error could crash an entire application!

FILE PROGRAM (in memory) TRY EXCEPT Exception Handling SUCCESS

1. File Handling

File-processing involves interacting with external files stored on secondary storage (e.g., hard drives, SSDs). In programming, files must be properly opened, read/written, and closed to ensure data is handled correctly.

📖 What are File-Processing Operations?

1.1 Common File Operations

Operation Description
Open File is opened in a specific mode: read (to read data), write (to overwrite data), or append (to add new data to the end)
Read Data (e.g., lines or records) is read from the file into memory
Write Data is written to the file (overwriting or appending depending on mode)
Close Ends access to the file and ensures all data is saved properly

1.2 Types of File Access

Access Type Description Common Use
Serial Access Records stored one after another, accessed in order they were added Logging events, transaction records
Sequential Access Records read from beginning to end, in order Batch processing, text files, reports
Random Access Records accessed directly using a key or file position Databases, indexed files
💡 Exam Tip

Remember: Serial = no specific order, just append; Sequential = read in order from start; Random = jump to any position directly!

SERIAL A B C D Append new here SEQUENTIAL Read from start to end RANDOM 3 Jump directly! Record Position: 0, 1, 2, 3

2. Python File Operations

2.1 Basic File Operations in Python

# Opening a file in different modes file = open("filename.txt", "r") # "r" = read mode file = open("filename.txt", "w") # "w" = write mode (overwrites) file = open("filename.txt", "a") # "a" = append mode # Reading from a file line = file.readline() # Read one line # Writing to a file file.write("Some text\n") # Write one line # Closing the file (IMPORTANT!) file.close()
⚠️ Important: Always Close Files!

Failing to close a file can lead to:

2.2 The with Statement (Best Practice)

Using the with statement automatically closes the file, even if an error occurs!

# Best practice: using 'with' statement with open("filename.txt", "r") as file: for line in file: print(line.strip()) # File is automatically closed here!

2.3 Serial Access Example (Logging)

Serial access writes data one after another, commonly used for logging events.

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)
"r" READ Read existing data File must exist "w" WRITE Overwrites file Creates if not exists "a" APPEND Adds to end Preserves existing ⚠️ Data lost!

3. Sequential & Random Access

3.1 Sequential Access (Reading All Records)

Sequential access reads records in order from start to end. Common for reports or summaries.

# Example: Reading student grades sequentially with open("students.txt", "r") as file: for line in file: name, grade = line.strip().split(",") print(f"Name: {name}, Grade: {grade}")
File contents (students.txt):
Alice,85
Bob,92
Charlie,78
Diana,95

3.2 Random Access (Direct Record Access)

Random access allows jumping directly to a specific record using its position (index). Requires reading all data first, then modifying.

# Example: Update a student's grade by index (record number) record_number = 4 # 5th record (0-indexed) # Read all records with open("students.txt", "r") as file: records = file.readlines() # Modify specific record name, grade = records[record_number].strip().split(",") records[record_number] = f"{name},90\n" # Update grade to 90 # Write all records back with open("students.txt", "w") as file: file.writelines(records)
📝 Random Access Steps
  1. Read all lines into a list using readlines()
  2. Access specific record by index: records[record_number]
  3. Modify the record as needed
  4. Write all records back to the file
Operation Python Example
Open open("file.txt", "r")
Read line file.readline() or for line in file:
Write file.write("text")
Close file.close() or use with open(...)
Random access lines = file.readlines() then use list indexing
SEQUENTIAL 1 2 3 4 Must go through 1→2→3→4 RANDOM 0 1 2 3 Jump directly to record 2

4. Exception Handling

4.1 What is Exception Handling?

📖 Definition

An exception is an unexpected event that disrupts normal program execution.

Exception handling is how a program detects and responds to these errors, allowing it to recover or shut down cleanly.

4.2 Why Use Exception Handling?

📝 Benefits of Exception Handling

4.3 Common Causes of Exceptions

Cause Example
Programming errors Uninitialised variables, logic errors
User errors Entering text instead of a number, invalid input
Hardware failure Lost connection to printer, disk error
File errors File not found, end-of-file reached unexpectedly
Mathematical errors Division by zero, overflow
❌ Common Mistake

Many beginners assume their code will always work correctly. Always anticipate potential errors! Users can enter unexpected data, files can be missing, and connections can fail.

Normal Flow Program runs normally EXCEPTION! Error detected CRASH! Program stops Without handling RECOVER Continue running With handling try-except Handler block

5. Try-Except in Python

5.1 Basic Try-Except Structure

try: file = open("data.txt", "r") line = file.readline() user_input = int(input("Enter a number: ")) result = 10 / user_input print("Result:", result) file.close() except FileNotFoundError: print("Error: File not found.") except ZeroDivisionError: print("Error: Cannot divide by zero.") except ValueError: print("Error: Please enter a valid number.") except Exception as e: print("An unexpected error occurred:", e)

5.2 Key Keywords

Keyword Purpose
try Starts a block of code that may raise an error
except Executes if a specific error occurs in the try block
finally Always executes, regardless of whether an error occurred
raise Manually triggers an exception

5.3 The Finally Block

The finally block always runs, whether an exception occurred or not. Perfect for cleanup operations like closing files.

try: file = open("data.txt", "r") # ... file operations ... except FileNotFoundError: print("File not found") finally: try: file.close() except: pass # File might not have opened
💡 Exam Tip

Use finally when you need to ensure cleanup happens (like closing files or connections). The with statement is often a better alternative for file handling!

try: Code that might fail Error? No Yes except: Handle the error finally: Always runs! Continue

6. Common Python Exceptions

6.1 Built-in Exception Types

Exception Cause Example
FileNotFoundError File doesn't exist open("missing.txt", "r")
ZeroDivisionError Division by zero 10 / 0
ValueError Invalid value for operation int("hello")
TypeError Wrong data type "text" + 5
IndexError List index out of range list[10] when list has 5 items
KeyError Dictionary key not found dict["missing_key"]
IOError Input/output operation fails Disk full, file locked

6.2 Handling Multiple Exceptions

try: number = int(input("Enter a number: ")) result = 100 / number print(f"Result: {result}") except ValueError: print("Please enter a valid number!") except ZeroDivisionError: print("Cannot divide by zero!") except: print("An unknown error occurred")
⚠️ Important: Order Matters!

Python checks except blocks in order. More specific exceptions should come before general ones. A bare except: catches everything, so it should be last!

6.3 Accessing Error Information

try: result = 10 / 0 except ZeroDivisionError as e: print(f"Error type: {type(e).__name__}") print(f"Error message: {e}") # Output: Error type: ZeroDivisionError # Error message: division by zero
Exception FileNotFoundError ValueError TypeError ZeroDivisionError IOError IndexError KeyError ← Catch specific exceptions first!

7. Pseudocode for File Operations

7.1 Basic Pseudocode File Operations

// Opening a file in pseudocode OPEN filename FOR mode // mode: READ, WRITE, APPEND // Reading from a file READ record FROM filename // Writing to a file WRITE record TO filename // Closing a file CLOSE filename // Random access - moving to specific position SEEK filename, recordNumber

7.2 Pseudocode Exception Handling

TRY // Code that might cause an error OPEN "data.txt" FOR READ READ record FROM "data.txt" SET result = 10 / userInput EXCEPT // Code to handle the error OUTPUT "An error occurred during file processing or division." CLOSE "data.txt" ENDTRY

7.3 Pseudocode Keywords

Keyword Purpose
TRY Starts a block of code that may raise an error
EXCEPT Executes if an error occurs in the TRY block
ENDTRY Marks the end of the exception handling structure

7.4 Example: Reading Records Sequentially

// Pseudocode for sequential reading TYPE Student DECLARE name : STRING DECLARE grade : INTEGER ENDTYPE DECLARE student : Student OPEN "students.txt" FOR READ WHILE NOT EOF("students.txt") READ student FROM "students.txt" OUTPUT student.name, student.grade ENDWHILE CLOSE "students.txt"
🧠 Memory Trick: File Operations

Remember the sequence: OPEN → READ/WRITE → CLOSE

Like a book: Open it → Read it → Close it!

Never forget to close - just like you wouldn't leave a book open!

PSEUDOCODE OPEN "file.txt" FOR READ WHILE NOT EOF("file.txt") READ record FROM "file.txt" OUTPUT record ENDWHILE CLOSE "file.txt" PYTHON with open("file.txt", "r") as f: for line in f: record = line.strip() print(record) # Auto-closed!

8. Exam-Style Questions (Part 1)

1. Explain the difference between serial, sequential, and random access when working with files. Give an example use case for each. [6 marks]

Answer:

  • Serial access: Records stored one after another, accessed in order added. No specific ordering. Use case: logging events, transaction records, audit trails
  • Sequential access: Records read from beginning to end in order. Must traverse from start. Use case: batch processing, generating reports, processing text files
  • Random access: Records accessed directly using key or position without reading preceding records. Use case: databases, indexed files, updating specific records

Additional points for deeper understanding:

  • Serial is fastest for appending new data (no searching required)
  • Sequential is efficient for processing ALL records
  • Random is best when you need specific records frequently
2. Write Python code to read a file called "data.txt" and print each line. Include appropriate exception handling. [5 marks]

Answer:

try: with open("data.txt", "r") as file: for line in file: print(line.strip()) except FileNotFoundError: print("Error: File not found") except IOError: print("Error: Could not read file")

Mark allocation:

  • Correct use of try-except (1 mark)
  • Opening file in read mode (1 mark)
  • Loop to read lines (1 mark)
  • Printing each line (1 mark)
  • Appropriate exception handling (1 mark)
3. Describe three reasons why exception handling is important in programming. [3 marks]

Answer:

  • Prevents crashes - Programs don't crash unexpectedly when errors occur
  • User-friendly error messages - Allows meaningful messages instead of cryptic system errors
  • Robustness - Makes programs more reliable and able to recover from errors gracefully

Additional points for deeper understanding:

  • Allows for clean resource cleanup (closing files, connections)
  • Separates error handling code from normal logic
  • Enables programs to continue running after non-fatal errors
4. Explain the purpose of the finally block in exception handling. Give an example of when it would be used. [4 marks]

Answer:

  • The finally block always executes, regardless of whether an exception occurred or not
  • It is used for cleanup operations that must happen in all cases
  • Common use: closing files, database connections, releasing resources
  • Example: Closing a file even if an error occurs during reading/writing

Example code:

file = None try: file = open("data.txt", "r") # Process file finally: if file: file.close()
5. Write pseudocode that opens a file, reads all records sequentially, and outputs each record. Include exception handling. [5 marks]

Answer:

TRY OPEN "records.txt" FOR READ WHILE NOT EOF("records.txt") READ record FROM "records.txt" OUTPUT record ENDWHILE CLOSE "records.txt" EXCEPT OUTPUT "Error processing file" ENDTRY

Mark allocation:

  • TRY-EXCEPT-ENDTRY structure (1 mark)
  • Opening file in READ mode (1 mark)
  • WHILE NOT EOF loop (1 mark)
  • READ and OUTPUT statements (1 mark)
  • Closing file and error message (1 mark)

8. Exam-Style Questions (Part 2)

6. A program asks the user to enter a number and then divides 100 by that number. Write Python code that handles the cases where the user enters non-numeric input or zero. [6 marks]

Answer:

try: user_input = int(input("Enter a number: ")) result = 100 / user_input print(f"Result: {result}") except ValueError: print("Error: Please enter a valid number") except ZeroDivisionError: print("Error: Cannot divide by zero")

Mark allocation:

  • try block structure (1 mark)
  • Converting input to integer (1 mark)
  • Division calculation (1 mark)
  • ValueError handling (1 mark)
  • ZeroDivisionError handling (1 mark)
  • Appropriate error messages (1 mark)
7. Explain the difference between opening a file in "w" mode versus "a" mode in Python. What happens to existing file contents in each case? [4 marks]

Answer:

  • "w" (write mode): Opens file for writing. If file exists, it is completely overwritten (all previous contents lost). If file doesn't exist, it is created.
  • "a" (append mode): Opens file for appending. New data is added to the end of existing contents. Existing contents are preserved. If file doesn't exist, it is created.

Additional points for deeper understanding:

  • Use "w" when you want to replace file contents completely
  • Use "a" for logging, adding records without losing existing data
  • Both modes create the file if it doesn't exist
  • "w" is destructive - always backup before using on important files!
8. What is the advantage of using the with statement when opening files in Python? [3 marks]

Answer:

  • The with statement automatically closes the file when the block exits
  • File is closed even if an exception occurs within the block
  • Eliminates the need to manually call close() and reduces the risk of leaving files open

Additional benefits:

  • Cleaner, more readable code
  • Prevents resource leaks
  • Ensures data is properly flushed to disk
9. Write Python code that uses random access to read and update the 3rd record (index 2) in a file called "products.txt". Each line contains a product name and price separated by a comma. [6 marks]

Answer:

# Read all records with open("products.txt", "r") as file: records = file.readlines() # Modify 3rd record (index 2) name, price = records[2].strip().split(",") records[2] = f"{name},199.99\n" # Update price # Write all records back with open("products.txt", "w") as file: file.writelines(records)

Mark allocation:

  • Reading all lines into list (1 mark)
  • Using correct index [2] (1 mark)
  • Parsing the record (1 mark)
  • Updating the record (1 mark)
  • Writing back to file (1 mark)
  • Correct file modes (1 mark)
10. A program needs to create a log file that records the time of each program run. Write Python code to append a timestamp to "log.txt" each time the program runs. [5 marks]

Answer:

from datetime import datetime # Get current timestamp timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") log_entry = f"Program run at: {timestamp}\n" # Append to log file with open("log.txt", "a") as file: file.write(log_entry)

Mark allocation:

  • Importing datetime (1 mark)
  • Getting current timestamp (1 mark)
  • Formatting log entry (1 mark)
  • Opening in append mode (1 mark)
  • Writing to file (1 mark)

9. Glossary

Exception
An unexpected event that disrupts normal program execution, such as an error or unusual condition that the program was not prepared to handle.
File Handle
A reference or pointer that allows a program to access and manipulate an open file. In Python, created when using open() function.
Serial Access
A file access method where records are stored and retrieved one after another in the order they were added. Often used for logging.
Sequential Access
A file access method where records are read from beginning to end in order. The file pointer moves sequentially through the file.
Random Access
A file access method that allows direct access to any record using its position or key, without reading preceding records.
Append Mode
A file opening mode that adds new data to the end of an existing file without deleting its current contents.
Write Mode
A file opening mode that creates a new file or overwrites an existing file completely. All previous contents are lost.
Read Mode
A file opening mode that allows reading data from an existing file. The file must exist, otherwise an error occurs.
Try Block
A code block that contains statements which might raise exceptions. If an exception occurs, execution jumps to the except block.
Except Block
A code block that executes when a specific exception occurs in the try block. Contains error handling code.
Finally Block
A code block that always executes after the try-except blocks, regardless of whether an exception occurred. Used for cleanup operations.
FileNotFoundError
A Python exception raised when attempting to open a file that does not exist in the specified location.
ZeroDivisionError
A Python exception raised when attempting to divide a number by zero.
ValueError
A Python exception raised when a function receives an argument with the correct type but an inappropriate value.
EOF (End of File)
A condition indicating that no more data can be read from a file because the end has been reached.
Context Manager
A Python object that manages resources using the 'with' statement, automatically handling setup and cleanup operations like opening and closing files.

10. Exam Success Tips (Part 1)

💡 File Modes - Remember the Differences
💡 File Access Types - Key Differences
💡 Exception Handling - Always Use It!
💡 The 'with' Statement - Best Practice
❌ Common Mistakes to Avoid
FILE MODES "r" → Read (must exist) "w" → Write (wipes!) "a" → Append (adds) ACCESS TYPES Serial → Append logs Sequential → Read all Random → Jump to record EXCEPTIONS try-except-finally FileNotFoundError ValueError, ZeroDiv

10. Exam Success Tips (Part 2)

🧠 Memory Trick: File Operations Sequence

O-R-W-C = "Our Records Will Continue"

Just like a library book: Open → Read → Close!

🧠 Memory Trick: Exception Keywords

T-E-F = "Try Every Failure"

💡 Answering Exam Questions
💡 Python vs Pseudocode
🌟 Quick Reference Table
Operation Python Pseudocode
Open for read open("f.txt", "r") OPEN "f.txt" FOR READ
Open for write open("f.txt", "w") OPEN "f.txt" FOR WRITE
Open for append open("f.txt", "a") OPEN "f.txt" FOR APPEND
Read line file.readline() READ record FROM file
Write line file.write("text") WRITE record TO file
Close file.close() CLOSE file
Random access lines[index] SEEK file, position

11. Key Takeaways

📌 File Operations Summary

File Access Types

File Modes

Best Practices

📌 Exception Handling Summary

Key Concepts

Common Exceptions

📌 Code Templates to Remember

Reading a file with exception handling:

try: with open("file.txt", "r") as f: for line in f: print(line.strip()) except FileNotFoundError: print("File not found")

User input with exception handling:

try: num = int(input("Enter number: ")) result = 100 / num except ValueError: print("Invalid number") except ZeroDivisionError: print("Cannot divide by zero")
OPEN r/w/a mode PROCESS read/write HANDLE exceptions CLOSE or with()