Python File Handling and Exception Handling —
Detailed Notes
■ FILE HANDLING
File handling in Python allows reading, writing, and modifying files stored permanently on disk.
1. Data Streams
Data streams are sequences of data flowing between a program and a file. Input streams read data,
and output streams write data.
Example - Writing and Reading a File
f = open("[Link]", "w") [Link]("Hello, Python File Handling!") [Link]() f =
open("[Link]", "r") print([Link]()) [Link]()
2. Access Modes
Mode Description
'r' Read mode
'w' Write mode (overwrites existing file)
'a' Append mode
'r+' Read and write
'b' Binary mode (used with other modes)
Example of File Methods
f = open("[Link]", "w+") [Link]("Riya is learning Python.") [Link](0)
print([Link]()) print("File position:", [Link]()) [Link]()
■■ EXCEPTION HANDLING
Exceptions are runtime errors that interrupt normal program flow. Python uses try-except blocks to
handle them gracefully.
Example - Handling Division Error
try: a = int(input("Enter number: ")) b = int(input("Enter another: "))
print("Result:", a / b) except ZeroDivisionError: print("Cannot divide by zero!")
except ValueError: print("Enter valid numbers!")
Raising and Using finally
try: f = open("[Link]") print([Link]()) except FileNotFoundError: print("File
not found!") finally: print("Execution completed.")
Generators Example
def counter(): for i in range(1, 5): yield i for num in counter(): print(num)
Generators return iterators and use the 'yield' keyword for lazy evaluation.
Summary Table
Concept Description Example
File Handling Managing files open(), read(), write()
Streams Data flow Input/Output stream
Access Modes Read/Write options 'r', 'w', 'a'
Exception Runtime error ZeroDivisionError
try-except Handle errors try: ... except:
finally Cleanup code finally:
raise Generate error manually raise ValueError()
Generator Yield-based function yield