Distinguish between serial, sequential, and random access
Write Python code to read from and write to files
Understand what exceptions are and why handling them is important
Use try-except blocks to handle errors gracefully
Identify common causes of exceptions (file errors, division by zero, invalid input)
Write robust programs that handle errors without crashing
📖 Prior Knowledge Required
Basic Python programming (variables, data types, operators)
Control structures (if statements, loops)
Functions and procedures
Understanding of data types (strings, integers, floats)
Basic understanding of file systems and storage
🌟 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!
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?
File-processing involves interacting with external files on secondary storage
Files must be properly opened, read/written, and closed
Different types of file access methods are used depending on needs
Ensures data persists beyond program execution
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!
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:
Data corruption - changes may not be saved
Memory leaks - system resources not released
Locked files - other programs cannot access the file
2.2 The with Statement (Best Practice)
Using the with statement automatically closes the file, even if an error occurs!
# Best practice: using 'with' statementwithopen("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"withopen("logfile.txt", "a") as file:
file.write(log)
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 sequentiallywithopen("students.txt", "r") as file:
for line in file:
name, grade = line.strip().split(",")
print(f"Name: {name}, Grade: {grade}")
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 recordswithopen("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 backwithopen("students.txt", "w") as file:
file.writelines(records)
📝 Random Access Steps
Read all lines into a list using readlines()
Access specific record by index: records[record_number]
Modify the record as needed
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
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.
User-friendly - Allows meaningful error messages instead of cryptic errors
Robustness - Makes programs more reliable
Clean recovery - Programs can handle problems gracefully
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.
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!
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
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!
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:
withopen("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 = Nonetry:
file = open("data.txt", "r")
# Process filefinally:
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 recordswithopen("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 backwithopen("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 filewithopen("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
"r" = Read only (file must exist)
"w" = Write (overwrites everything! Creates if not exists)
"a" = Append (adds to end, preserves existing data)
"r+" = Read AND write (file must exist)
Remember: "w" = Wipes everything! Be careful!
💡 File Access Types - Key Differences
Serial: Just append to end - no searching, no ordering. Fast for adding, slow for finding.
Sequential: Must read from start - like reading a book from page 1.
Random: Jump to any position - like opening a book to any page directly.
Exam question: "Which access method for a log file?" → Serial (just append)
💡 Exception Handling - Always Use It!
Wrap file operations in try-except blocks
Handle specific exceptions first, then general ones
Common exceptions to know: FileNotFoundError, ValueError, ZeroDivisionError, TypeError
Use finally for cleanup (or better, use with statement)
💡 The 'with' Statement - Best Practice
Always prefer with open(...) as file: over manual open/close
Automatically closes file, even if exception occurs
Cleaner code - no need for try-finally just for closing
Exam answer using 'with' shows best practice knowledge
❌ Common Mistakes to Avoid
Forgetting to close files - can cause data loss and resource leaks
Using "w" instead of "a" - wipes your data!
Not handling exceptions - program crashes on errors
Wrong exception type - FileNotFoundError for missing files, ValueError for bad input
Bare except: catches everything - be specific when possible
10. Exam Success Tips (Part 2)
🧠 Memory Trick: File Operations Sequence
O-R-W-C = "Our Records Will Continue"
Open the file
Read or Write data
Close the file
Just like a library book: Open → Read → Close!
🧠 Memory Trick: Exception Keywords
T-E-F = "Try Every Failure"
Try the risky code
Except when errors occur
Finally always runs
💡 Answering Exam Questions
"Describe" = Give step-by-step details
"Explain" = Give reasons WHY something happens
"Write code" = Include all necessary statements
Mark allocation = Number of distinct points needed (4 marks = 4 points)
Always show exception handling when writing file code
💡 Python vs Pseudocode
Python: with open("file.txt", "r") as f:
Pseudocode: OPEN "file.txt" FOR READ
Python: try: ... except: ...
Pseudocode: TRY ... EXCEPT ... ENDTRY
Know both - exam may ask for either!
🌟 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
Serial: Append to end, no ordering - use for logs
Sequential: Read start to end - use for reports
Random: Direct access by position - use for databases
File Modes
"r" = Read mode (file must exist)
"w" = Write mode (overwrites, creates if needed)
"a" = Append mode (adds to end, preserves existing)
Best Practices
Always close files - use with statement
Use exception handling for file operations
Check if files exist before reading
Be careful with "w" mode - it deletes existing content!
📌 Exception Handling Summary
Key Concepts
Exception = Unexpected error during execution
try = Code that might fail
except = Code to handle errors
finally = Always executes (cleanup)
Common Exceptions
FileNotFoundError - File doesn't exist
ValueError - Invalid value for operation
ZeroDivisionError - Division by zero
TypeError - Wrong data type
📌 Code Templates to Remember
Reading a file with exception handling:
try:
withopen("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")