Module 3

File Handling & Exceptions

Master file I/O operations and robust error handling for secure applications

Learning Objectives

Read and write files safely

Handle exceptions and errors gracefully

Work with JSON and CSV data formats

Implement context managers

Build secure file operations

Create custom exceptions

File Handling Fundamentals

Reading File Contents
Different methods to read files efficiently

Python provides multiple ways to read files. Choose the method based on file size and use case.

python
file = open('data.txt', 'r')
content = file.read()
file.close()

with open('data.txt', 'r') as file:
    content = file.read()

with open('data.txt', 'r') as file:
    for line in file:
        print(line.strip())

with open('data.txt', 'r') as file:
    lines = file.readlines()

Exception Handling

Try-Except Blocks
Catching and handling exceptions
python
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

try:
    file = open('missing.txt', 'r')
except FileNotFoundError:
    print("File not found")
except Exception as e:
    print(f"Error: {e}")
finally:
    print("Cleanup code here")

Context Managers & With Statement

Automatic Resource Management
Using context managers for safe resource handling

Context managers ensure resources are properly cleaned up, even if errors occur.

python
with open('file.txt', 'r') as f:
    content = f.read()

import json
with open('data.json', 'r') as f:
    data = json.load(f)

class FileLogger:
    def __init__(self, filename):
        self.filename = filename
        self.file = None
    
    def __enter__(self):
        self.file = open(self.filename, 'a')
        return self.file
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.file:
            self.file.close()
        if exc_type:
            print(f"Exception occurred: {exc_type.__name__}")
        return False

with FileLogger('app.log') as log:
    log.write('Application started\n')

Working with Data Formats

Working with JSON
Parse and serialize JSON data safely
python
import json

data = {"user": "alice", "role": "admin", "active": True}
json_string = json.dumps(data, indent=2)

with open('config.json', 'w') as f:
    json.dump(data, f, indent=2)

with open('config.json', 'r') as f:
    loaded_data = json.load(f)

try:
    parsed = json.loads(json_string)
except json.JSONDecodeError as e:
    print(f"Invalid JSON: {e}")

class SecurityConfig:
    def to_json(self):
        return json.dumps(self.__dict__)
    
    @classmethod
    def from_json(cls, json_str):
        data = json.loads(json_str)
        return cls(**data)

Hands-On Project

Build a Secure Log Analyzer
Create a tool to parse and analyze security logs with error handling

Design a log analyzer that reads security event files, parses entries, filters by severity, and generates reports.

python
import json
from datetime import datetime

class LogAnalyzer:
    def __init__(self, log_file):
        self.log_file = log_file
        self.events = []
    
    def parse_logs(self):
        try:
            with open(self.log_file, 'r') as f:
                for line in f:
                    try:
                        event = json.loads(line)
                        self.events.append(event)
                    except json.JSONDecodeError:
                        print(f"Skipping invalid JSON: {line}")
        except FileNotFoundError:
            print(f"Error: Log file not found")
        except Exception as e:
            print(f"Error reading logs: {e}")
    
    def filter_by_severity(self, severity):
        return [e for e in self.events if e.get('severity') == severity]
    
    def generate_report(self, output_file):
        try:
            with open(output_file, 'w') as f:
                f.write(f"Log Analysis Report\n")
                f.write(f"Total Events: {len(self.events)}\n")
                f.write(f"Critical: {len(self.filter_by_severity('CRITICAL'))}\n")
                f.write(f"High: {len(self.filter_by_severity('HIGH'))}\n")
        except IOError as e:
            print(f"Error writing report: {e}")

analyzer = LogAnalyzer('security.log')
analyzer.parse_logs()
analyzer.generate_report('report.txt')