Bird
0
0

Which of the following code snippets correctly uses a context manager to open a file for reading?

easy📝 Syntax Q3 of 15
Python - Context Managers
Which of the following code snippets correctly uses a context manager to open a file for reading?
Awith open('file.txt', 'r') as f: data = f.read()
Bopen('file.txt', 'r') as f: data = f.read()
Cwith open('file.txt', 'r'): data = read()
Dfile = open('file.txt', 'r') with file: data = file.read()
Step-by-Step Solution
Solution:
  1. Step 1: Identify correct 'with' syntax

    The 'with' statement must be followed by an expression and 'as' to assign the resource.
  2. Step 2: Check each option

    with open('file.txt', 'r') as f: data = f.read() correctly uses 'with open(...) as f:' and reads data.
  3. Final Answer:

    with open('file.txt', 'r') as f: data = f.read() -> Option A
  4. Quick Check:

    Correct 'with' syntax includes 'as' [OK]
Quick Trick: 'with open(...) as var:' is correct syntax [OK]
Common Mistakes:
  • Omitting 'with' keyword
  • Missing 'as' keyword
  • Not assigning the file object

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes