Practice & Assessment
Test your understanding of File I/O and Error Handling
Multiple Choice Questions
5Why should you always use the `with` statement when opening files?
What is the difference between `json.dumps` and `json.dump`?
What is wrong with `except:` (bare except) in Python?
Why should CSV files be opened with `newline=""`?
What does `raise RuntimeError('msg') from e` do differently than `raise RuntimeError('msg')`?
Coding Challenges
1JSON config file reader with validation
Write a function `load_config(filepath)` that reads a JSON file, validates it contains required keys ('host', 'port', 'debug'), raises a custom `ConfigError` if the file is missing or malformed or if required keys are absent. Return the config dict if valid. Test with a valid file, a missing file, invalid JSON, and a file missing required keys. Input: file path string. Output: dict or raised custom exception. Estimated time: 20-25 minutes.
Mini Project
CSV Contact Book with JSON Backup
Build a CLI contact book. Contacts have name, email, and phone. Store data in a CSV file (contacts.csv) using DictReader/DictWriter. Support operations: add contact, search by name (partial match), delete by name, list all contacts, and export all contacts to a JSON backup file (contacts.json). Wrap all file operations in try/except blocks with descriptive custom exceptions (ContactNotFoundError, DuplicateContactError). All changes persist to disk after each operation. Demonstrate all module skills: file I/O, JSON, CSV, custom exceptions, and the with statement.
