A developer writes a Python script to read a configuration file. Which code snippet correctly opens the file 'config.json' for reading and ensures the file is closed after use?
Trap 1: open('config.json', 'r') as f:\n data = f.read()
Missing the 'with' keyword; syntax error.
Trap 2: with open('config.json', 'r') as f, data = f.read()
Syntax error; cannot assign variable inside with statement like that.
Trap 3: file = open('config.json', 'r')\ndata = file.read()\nfile.close()
This manually closes the file but does not guarantee closure if an exception occurs before file.close().
- A
with open('config.json', 'r') as f:\n data = f.read()
Using with ensures proper acquisition and release of resources.
- B
open('config.json', 'r') as f:\n data = f.read()
Why wrong: Missing the 'with' keyword; syntax error.
- C
with open('config.json', 'r') as f, data = f.read()
Why wrong: Syntax error; cannot assign variable inside with statement like that.
- D
file = open('config.json', 'r')\ndata = file.read()\nfile.close()
Why wrong: This manually closes the file but does not guarantee closure if an exception occurs before file.close().