← Back to libraryQuestion 197 of 468
🐍PythonIntermediate

File Handling and the with Statement

📌 Definition:

Python reads/writes files with open(), and the with statement (context manager) guarantees the file is closed automatically even if an error occurs. This is the standard, safe pattern.

📖 Detailed Explanation:

with open('data.json') as f: data = f.read() opens the file, binds it to f, and closes it when the block exits — no explicit f.close() and no leak on exceptions. Modes: 'r' read, 'w' write (truncate), 'a' append, 'b' binary, 'r+' read/write. For structured data, pair with the json/csv modules (json.load(f), csv.DictReader(f)). Context managers generalize beyond files (locks, DB connections, Selenium waits), and you can write your own with __enter__/__exit__ or contextlib. Always prefer with over manual open/close.

🔑 Key Points:
  • with open(...) as f: auto-closes the file, even on error
  • Modes: r/w/a/b/r+ (w truncates!)
  • Pair with json/csv modules for structured data
  • Context managers generalize to locks, connections, etc.
🌍 Real-World Example:

Loading test data safely: with open('users.json') as f: users = json.load(f) — the file closes automatically, avoiding leaked handles across a large suite.

🎯 Scenario-Based Interview Question:

Why is with open('log.txt') as f: preferred over f = open('log.txt') ... f.close()?