Lesson 2.5: File Handling & Exception Handling in Python
File handling allows you to create, read, write, and delete files. Exception handling ensures your program doesn’t crash when errors occur.
1. File Handling
Opening a File
File Modes
-
"r"→ Read (default, file must exist) -
"w"→ Write (creates new file or overwrites existing) -
"a"→ Append (adds data to file) -
"x"→ Create new file (error if file exists) -
"b"→ Binary mode (for images, videos, etc.) -
"t"→ Text mode (default)
Reading a File
Writing to a File
Appending to a File
With Statement (Best Practice)
Automatically closes file:
2. Exception Handling
Try-Except Block
Finally Block
Code that always runs:
✅ In Summary
-
Use
open()with proper mode (r,w,a, etc.). -
Always close file (or use
with). -
Use
try-except-finallyto handle runtime errors safely.
