Unit 5: File Handling & Robust Exception Handling in Python
Stream I/O mechanics, context managers, structured CSV data processing, exception propagation hierarchies, and custom user-defined error classes
Data persistence and fault tolerance represent two critical pillars of production-grade software engineering. In the SPPU autonomous curriculum (ADES204 Unit 5), students are tested on how Python interfaces with disk files, handles character encodings, and intercepts runtime anomalies through structured exception hierarchies. This unit regularly features high-weightage questions (14–16 marks) covering file cursor manipulation via seek() and tell(), CSV dataset extraction, and try-except-else-finally flow control.
1. File Modes & Stream Architecture
In Python, disk files are accessed as stream objects via the built-in open(filename, mode) function. Choosing the appropriate access mode determines whether the pointer starts at the beginning or end of the file, whether existing content is overwritten, and whether the data is treated as text strings or raw binary bytes:
📂 Python File Access Modes Reference
'r': Read mode (default). Fails withFileNotFoundErrorif the target file does not exist. Positioned at start.'w': Write mode. Truncates the target file to 0 bytes or creates a new file if nonexistent. Positioned at start.'a': Append mode. Leaves existing data intact; all new writes are appended to the file's end. Creates file if nonexistent.'r+': Read and Write mode. File must exist; pointer starts at the beginning without truncating.'w+': Write and Read mode. Truncates file immediately to 0 bytes or creates new file.'rb' / 'wb': Binary read/write modes. Essential for serialized ML weights, image assets, and compressed archives.
2. Reading, Writing, and the Context Manager (`with` Statement)
Manually calling file.close() is error-prone—if an unexpected exception occurs during file reading or writing, the file handle remains leaked in operating system memory. The with statement establishes a context manager adhering to the Python context protocol (__enter__ and __exit__), guaranteeing that the file descriptor is closed immediately upon exiting the block, even under fatal exceptions.
# Writing logs using with statement with open("training_metrics.txt", "w", encoding="utf-8") as f: f.write("Epoch,Loss,Accuracy\n") f.writelines([ "1,0.693,0.52\n", "2,0.481,0.78\n", "3,0.214,0.94\n" ]) # Reading and navigating the stream cursor with open("training_metrics.txt", "r") as f: header = f.readline().strip() print(f"Header detected: {header}") print(f"Current byte position: {f.tell()}") # Rewind cursor back to the start f.seek(0) all_lines = f.readlines() print(f"Total lines read after seek(0): {len(all_lines)}")
3. CSV Data Processing using Python's `csv` Module
In AI and Data Science engineering, datasets frequently arrive in Comma-Separated Values (CSV) format. Python's standard csv library handles quoting, commas inside text, and row conversions cleanly.
import csv # Parsing student dataset using DictReader csv_data = """PRN,Student_Name,SGPA,Attendance PRN201,Aditi Kulkarni,9.45,92 PRN202,Tanmay Joshi,8.80,85 PRN203,Rohan Deshmukh,9.15,96""" with open("students.csv", "w", newline="") as f: f.write(csv_data) with open("students.csv", "r") as f: reader = csv.DictReader(f) print("Eligible Distinction Students (SGPA >= 9.0):") for row in reader: if float(row["SGPA"]) >= 9.0: print(f" - {row['Student_Name']} ({row['PRN']}): {row['SGPA']}")
4. Exception Handling Architecture: try, except, else, and finally
An exception is an event occurring during program execution that disrupts normal instruction flow. In Python, all standard exceptions inherit from the root BaseException → Exception class.
🛡️ The Complete 4-Part Exception Construct
try: Encloses hazardous statements that could potentially trigger a runtime exception.except ExceptionType as err: Intercepts matching exceptions, preventing program crash and enabling graceful recovery.else: Executes strictly when thetryblock completes without encountering any exceptions.finally: Guaranteed to execute in all scenarios—regardless of whether an exception occurred, was handled, or remained unhandled. Indispensable for releasing database locks, network sockets, or external hardware connections.
def safe_divide_and_record(val1, val2, log_file): try: num1 = float(val1) num2 = float(val2) result = num1 / num2 except ZeroDivisionError as ze: print(f"[Error] Arithmetic fault: {ze}") return None except ValueError as ve: print(f"[Error] Non-numeric input supplied: {ve}") return None else: print(f"[Success] Computation succeeded: {num1} / {num2} = {result:.4f}") return result finally: # Cleanup code executed always print("[Audit] Evaluation cycle terminated.\n") safe_divide_and_record("100", "4", "audit.log") safe_divide_and_record("50", "0", "audit.log") safe_divide_and_record("ten", "2", "audit.log")
5. Raising Exceptions & Custom User-Defined Exception Classes
Developers can trigger exceptions programmatically using the raise keyword. To represent domain-specific failures (such as invalid dataset shapes, out-of-range sensor readings, or invalid authentication tokens), create custom classes inheriting directly from Exception.
class InvalidDatasetError(Exception): """Raised when input dataset violates training shape requirements.""" def __init__(self, row_count, min_required=100): self.rows = row_count self.min_req = min_required super().__init__(f"Dataset has only {row_count} rows. Model requires at least {min_required} samples.") def initiate_training_pipeline(samples): if len(samples) < 100: raise InvalidDatasetError(len(samples), min_required=100) print("Training started successfully...") try: initiate_training_pipeline([1.2, 3.4, 5.6]) except InvalidDatasetError as e: print(f"Caught Domain Error: {e}")
6. Typical Autonomous ETE Exam Questions & Marking Schemas
Q1: Differentiate between seek() and tell() with an illustrative code snippet. (5 Marks)
Answer Strategy: Define tell() as the method returning the current byte position of the file read/write pointer as an integer. Define seek(offset, whence) as the method repositioning the cursor to a specific byte location (where whence=0 is beginning of file, 1 is current position, and 2 is end of file in binary mode). Provide a 5-line code snippet showing pointer tracking after writing and rewinding.
Q2: Explain the significance of the finally block and the with statement in resource management. (6 Marks)
Answer Strategy: Highlight the concept of operating system file handle leakage when unhandled exceptions bypass standard close() statements. Contrast how finally guarantees closure through explicit error handling, while the with context manager abstracts this pattern through Python's __enter__ and __exit__ protocol.
📥 Printable Chapter Reference (PDF Supplement)
Prefer an offline physical copy for revision or exam night preparation? You can download our verified, printer-friendly PDF synthesis for Unit 5 below:
🔗 Related Study Resources
- FY Semester 2 Academic Library — Complete collection of course units and solved papers
- Python Unit 3: Control Structures & Loops — Master branching, iterators, and modular functions
- Python Unit 6: Object-Oriented Programming — Learn classes, inheritance, and magic methods
- ETE Preparation Strategy — 10-day battle-tested revision roadmap for engineering exams