10. Files & Exceptions
1. Simple Definition & Meaning
Files: How Python reads text documents or saves data permanently.
Exceptions: How Python handles errors safely without crashing the whole program.
2. Real-World Examples
- Example 1 (Files): Just like you open a notebook to read a story, Python uses
open()to read a file. - Example 2 (Exceptions): If you try to divide a pizza by zero people, your brain gets confused. Python gets confused too! Exceptions are like saying "If an error happens, just say 'Oops!' instead of shutting down."
3. Important Points
- Use
with open('filename.txt') as file:so you don't have to remember to close the file later. - Use
try:andexcept:blocks to catch errors.
📝 Exam Notes (Quick Revision)
- Reading:
contents = file.read() - JSON: Use the
jsonmodule to save and load complex data structures like lists and dictionaries. - Try-Except: Prevents crashes when errors like
FileNotFoundErroroccur.