1. File Modes & Context Managers (`with open(...)`)
Deterministic Resource Release
- Modes: "r" (read, default), "w" (write, truncates file), "a" (append), "r+" (read/write), "b" (binary mode like "rb" or "wb").
- The `with open(...) as f:` syntax binds a context manager.
- Upon exiting the block (by finishing, return, or exception), Python automatically invokes `f.__exit__()`, flushing buffers and closing the file descriptor.
# Demonstrating file operations with context manager
content = "Line 1: Computer Science\nLine 2: Data Structures\n"
# Reading line by line
for line in content.splitlines():
print("Processed:", line)
💡 Key Takeaway: Always use with open(...) to ensure file descriptors are never leaked in memory.